2020年4月25日土曜日

Perl - サブルーチン - 数値のリスト、合計、範囲演算子

コード

```#!/usr/bin/env perl
use strict;
use warnings;
use v5.28;

say '1.';

sub total {
my \$result = 0;
for (@_) {
\$result += \$_;
}
\$result;
}

my @fred = qw{1 3 5 7 9};
my \$fred_total = total(@fred);
say "The total of \@fred is \$fred_total.";
print "Enter some numbers on separate lines: ";
my \$user_total = total(<STDIN>);
say "The total of those numbers is \$user_total.";

say "2.";
my \$total = total 1..1000;
say "1から1,000までの合計は\$total。";

say "おまけ";
my @nums = (1, 3, 5, 7, 9);
say total @nums;
```

```% ./sample1.pl
1.
The total of @fred is 25.
Enter some numbers on separate lines: 1
2
3
4
5
6
7
8
9
10
The total of those numbers is 55.
2.
1から1,000までの合計は500500。
おまけ
25
% ./sample1.pl
1.
The total of @fred is 25.
Enter some numbers on separate lines: 1
The total of those numbers is 1.
2.
1から1,000までの合計は500500。
おまけ
25
% ./sample1.pl
1.
The total of @fred is 25.
Enter some numbers on separate lines: -1
1
The total of those numbers is 0.
2.
1から1,000までの合計は500500。
おまけ
25
% ./sample1.pl
1.
The total of @fred is 25.
Enter some numbers on separate lines: The total of those numbers is 0.
2.
1から1,000までの合計は500500。
おまけ
25
%
```