4.12.1 練習問題

配列の合計を出すサブルーチンを作る問題。

#!/usr/bin/perl -w
use strict;

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: ";
my $user_total = &total();
print "The total of those numbers is $user_total.\n";


sub total {
  my $sum = 0;
  foreach (@_) {
    $sum += $_;
  }
  $sum;
}

変数名まで解答と一緒。:-)