開発環境
- OS X Lion - Apple(OS)
- TextWrangler(Text Editor) (BBEditの機能制限無料版、light版)
- Script言語:Perl
『続・初めてのPerl 改訂版』(Randal L. Schwartz, brian d foy, Tom Phoenix 著、伊藤 直也、田中 慎司、吉川 英興 監訳、株式会社ロングテール/長尾 高弘 訳、オライリー・ジャパン、2006年、ISBN4-87311-305-9) の4章(リファレンス入門), 4.9(練習問題)1、2を解いてみる。
1.
問題の式のうち異なる参照先は1つで、${$ginger[2]}[1]。
2.
やり方の1つ。(「やり方は何通りもある」(TIMTOWTDI(There Is More Than One Way To Do It.)))
コード(TextWrangler)
#!/usr/bin/env perl
use strict;
use warnings;
my @gilligan = qw(red_shirt hat lucky_socks water_bottle);
my @skipper = qw(blue_shirt hat jacket preserver sunscreen);
my @professor = qw(sunscreen water_bottle slide_rule batteries radio);
my %all = (
Gilligan => \@gilligan,
Skipper => \@skipper,
Professor => \@professor,
);
check_items_for_all(\%all);
sub check_required_items {
my $who = shift;
my $items = shift;
my @required = qw(preserver sunscreen water_bottle jacket);
my @missing = ();
for my $item(@required){
unless (grep $item eq $_, @$items){
print "$who is missing $item.\n";
push @missing, $item;
}
}
if (@missing) {
print "Adding @missing to @$items for $who.\n";
push @$items, @missing;
}
}
sub check_items_for_all{
my $all = shift;
for(keys %$all){
check_required_items($_, $all->{$_});
}
}
入出力結果(Terminal)
$ ./sample.pl Gilligan is missing preserver. Gilligan is missing sunscreen. Gilligan is missing jacket. Adding preserver sunscreen jacket to red_shirt hat lucky_socks water_bottle for Gilligan. Skipper is missing water_bottle. Adding water_bottle to blue_shirt hat jacket preserver sunscreen for Skipper. Professor is missing preserver. Professor is missing jacket. Adding preserver jacket to sunscreen water_bottle slide_rule batteries radio for Professor. $
0 コメント:
コメントを投稿