開発環境
- OS X Lion - Apple(OS)
- TextWrangler(Text Editor) (BBEditの機能制限無料版、light版)
- Script言語:Perl
『初めてのPerl 第6版』(Randal L. Schwartz, Tom Phoenix, brian d foy 共著、近藤 嘉雪 訳、オライリー・ジャパン、2012年、ISBN978-4-87311-567-2) の4章(サブルーチン)、4.12(練習問題)3を解いてみる。
3.
コード(TextWrangler)
sample.pl
#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
binmode STDOUT, ':encoding(UTF-8)';
binmode STDIN, ':encoding(UTF-8)';
sub total{
my $result = 0;
for(@_){
$result += $_;
}
$result;
}
sub average{
total(@_) / @_;
}
sub above_average{
my @result = ();
my $average = average(@_);
for(@_){
push @result, $_ if $_ > $average;
}
@result;
}
my @fred = above_average(1..10);
print "\@fred is @fred\n";
print "(Should be 6 7 8 9 10)\n";
my @barney = above_average(100, 1..10);
print "\@barney is @barney\n";
print "(Should be just 100)\n";
入出力結果(Terminal)
$ ./sample.pl @fred is 6 7 8 9 10 (Should be 6 7 8 9 10) @barney is 100 (Should be just 100) $
解答ではabove_averageのループの制御変数でデフォルトの$_を使ってないのなんでだろう。。ただの可読性の問題かな〜
0 コメント:
コメントを投稿