いっきに練習問題まで。
4-2 & 4-3 引数リストに含まれる数値の合計を返すサブルーチンを作る
単純に、
use strict; #問題のサブルーチン sub total{ my @nums = @_; my $sum = 0; foreach (@nums) { $sum += $_; } $sum; } # 4-1 my @fred = qw{1 3 5 7 9}; my $fred_total = &total(@fred); print "The total of \@fred is $fred_total.\n"; print "Enter some numbers on separate lines\n"; my $user_total = &total(<STDIN>); print "The total of those numbers is $user_total.\n"; # 4-2 my $thousand_total = &total(1..1000); print "The total of a thousand numbers is $thousand_total.\n";
とした。解答を見ても似たような解のよう。$sumは0で初期化するとundefを返すから良くないのね。
もう6章くらいまで読んだのでちゃっちゃまとめていきたい。

- 作者: ランダル・L.シュワルツ,トムフェニックス,Randal L. Schwartz,Tom Phoenix,近藤嘉雪
- 出版社/メーカー: オライリージャパン
- 発売日: 2003/05
- メディア: 単行本
- 購入: 15人 クリック: 474回
- この商品を含むブログ (294件) を見る