2020年7月22日水曜日

開発環境

続・初めてのPerl 改訂第2版 (Randal L. Schwartz(著)brian d foy(著)Tom Phoenix(著)伊藤 直也(監修)長尾 高弘(翻訳)、オライリージャパン)の8章(ファイルハンドルへのリファレンス)、8.7(練習問題 )1の解答を求めてみる。

コード

#!/usr/bin/env perl
use strict;
# use warnings;
use Time::Moment;
use IO::Tee;

my $out = $ARGV[0];
my $string = "";
my $fh;
if ($out eq "string") {
    open $fh, '>', \$string;
} elsif ($out eq "file") {
    open $fh, '>', "tmp.txt";
} elsif ($out eq "both") {
    open my $string_fh, '>', \$string;
    open my $out_fh, '>', "tmp.txt";
    $fh = IO::Tee->new($string_fh, $out_fh);
} else {
    die "usage: command (string|file|both)"
}
my $dt = Time::Moment->now;

printf $fh "%d月%d日%s\n", $dt->month, $dt->day_of_month,
                      qw(undef 月 火 水 木 金 土 日)[$dt->day_of_week] . "曜日";
print $string if $out =~ /(string|both)/;

入出力結果(Zsh、PowerShell、Terminal)

% ./sample1.pl
usage: command (string|file|both) at ./sample1.pl line 19.
% ./sample1.pl string
7月22日水曜日
% ls tmp.txt
ls: tmp.txt: No such file or directory
% ./sample1.pl file
% ls tmp.txt       
tmp.txt
% cat tmp.txt 
7月22日水曜日
% rm tmp.txt 
% ./sample1.pl both
7月22日水曜日
% cat tmp.txt 
7月22日水曜日
% 

0 コメント:

コメントを投稿