開発環境
- OS X Lion - Apple(OS)
- BBEdit - Bare Bones Software, Inc., Emacs(Text Editor)
- プログラミング言語: Perl
『続・初めてのPerl 改訂版』(Randal L. Schwartz, brian d foy, Tom Phoenix 著、伊藤 直也、田中 慎司、吉川 英興 監訳、株式会社ロングテール/長尾 高弘 訳、オライリー・ジャパン、2006年、ISBN4-87311-305-9)の8章(ファイルハンドルへのリファレンス)の8.6(練習問題)1を解いてみる。
その他参考書籍
1.
コード(BBEdit)
sample.pl
#!/usr/bin/env perl use strict; use warnings; use 5.016; use utf8; binmode STDOUT, ':utf8'; binmode STDIN, ':utf8'; binmode STDERR, ':utf8'; use IO::Tee; my $dst; my $fh; my $string; print "出力先を選択(file/scalar/both): "; while (1) { chomp($dst = <STDIN>); last if $dst =~ /^(file|scalar|both)$/; print "出力先はfile/scalar/bothのいずれかを選択してください\n"; } given ($dst) { when ( 'file' ) {open $fh, '>', 'date.log' or die $!;} when ( 'scalar' ) {open $fh, '>', \$string or die $1;} when ( 'both' ) { open my $file_fh, '>', 'date.log' or die $!; open my $scalar_fh, '>', \$string or die$!; $fh = IO::Tee->new( $file_fh, $scalar_fh); } } print $fh localtime . "\n"; print STDOUT $string if $dst =~ /^(scalar|both)$/;
入出力結果(Terminal)
$ ./sample.pl 出力先を選択(file/scalar/both): scalar Thu Sep 12 12:59:44 2013 $ ./sample.pl 出力先を選択(file/scalar/both): file $ cat date.log Thu Sep 12 12:59:54 2013 $ rm date.log $ ./sample.pl 出力先を選択(file/scalar/both): scalar Thu Sep 12 13:00:06 2013 $ ./sample.pl 出力先を選択(file/scalar/both): both Thu Sep 12 13:00:12 2013 $ cat date.log Thu Sep 12 13:00:12 2013 $ ./sample.pl 出力先を選択(file/scalar/both): a 出力先はfile/scalar/bothのいずれかを選択してください ^C $
ちなみにpython3.3の場合。
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3 ## Copyright (C) 2013 by kamimura #-*- coding: utf-8 -*- # pythonでperlのIO::Teeみたいなモジュールがあるか分からなかったので工夫のない単純な方法で import re import datetime td = datetime.datetime.today().ctime() dst = input('出力先を選択(file/str/both): ') s = "" while True: if re.match(r"(file|str|both)", dst): break dst = input('出力先はfile/str/bothのいずれかを選択してください') if dst == 'file': with open('date.log', 'w') as f: f.write('{0}\n'.format(td)) elif dst == "str": s = td else: with open('date.log', 'w') as f: f.write('{0}\n'.format(td)) s = td if s: print(s)
入出力結果(Terminal)
$ ./sample.py 出力先を選択(file/str/both): file $ cat date.log Thu Sep 12 13:15:24 2013 $ rm date.log $ ./sample.py 出力先を選択(file/str/both): str Thu Sep 12 13:15:37 2013 $ ./sample.py 出力先を選択(file/str/both): both Thu Sep 12 13:15:45 2013 $ cat date.log Thu Sep 12 13:15:45 2013 $ ./sample.py ]出力先を選択(file/str/both): a 出力先はfile/str/bothのいずれかを選択してください^CTraceback (most recent call last): File "./sample.py", line 16, in <module> dst = input('出力先はfile/str/bothのいずれかを選択してください') KeyboardInterrupt $
0 コメント:
コメントを投稿