2012年10月26日金曜日

開発環境

『続・初めてのPerl 改訂版』(Randal L. Schwartz, brian d foy, Tom Phoenix 著、伊藤 直也田中 慎司吉川 英興 監訳、株式会社ロングテール/長尾 高弘 訳、オライリー・ジャパン、2006年、ISBN4-87311-305-9) の8章(ファイルハンドルへのリファレンス), 8.6(練習問題)1を解いてみる。

その他参考書籍

1.

まず、準備としてMacPortsでモジュール、IO::Teeをインストール。

$ sudo port -v install p5.16-io-tee

モジュールのインストールってcpanから直接した方がいいのかな。。

コード(TextWrangler)

sample.pl

#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use 5.016;
binmode STDIN, ':utf8';
binmode STDOUT, ':utf8';
use IO::Tee;

my $fh;
my $string;

while(1){
  print "出力先(ファイル(f)、文字列(s)、両方(t))を入力: ";
  chomp(my $out = <STDIN>);
  given($out){
    when(/^f$/i){
      open $fh, ">", "log";
    }
    when(/^s$/i){
      open $fh , ">", \$string;
    }
    when(/^t$/i){
      open my $log_fh, ">", "log";
      open my $scalar_fh, ">",\$string;
      $fh = IO::Tee->new($log_fh, $scalar_fh);
    }
    default {
      print "入力を確認してください。\n";
      next;
    }
  }
  last;
}

my $date = localtime;
my $wday = (localtime)[6];
print $fh "date: $date\nwday: $wday\n";
print STDOUT $string if $string;

入出力結果(Terminal)

$ rm log
$ ./sample.pl
出力先(ファイル(f)、文字列(s)、両方(t))を入力: f
$ cat log
date: Fri Oct 26 17:30:51 2012
wday: 5
$ ./sample.pl
出力先(ファイル(f)、文字列(s)、両方(t))を入力: s
date: Fri Oct 26 17:30:55 2012
wday: 5
$ rm log
$ ./sample.pl
出力先(ファイル(f)、文字列(s)、両方(t))を入力: t
date: Fri Oct 26 17:31:06 2012
wday: 5
$ cat log
date: Fri Oct 26 17:31:06 2012
wday: 5
$

0 コメント:

コメントを投稿