2012年5月16日水曜日

開発環境

『初めてのPerl 第5版』(Randal L. Schwartz, Tom Phoenix, brian d foy 共著、近藤 嘉雪 訳、オライリー・ジャパン、2009年、ISBN978-4-87311-427-9) の4章(サブルーチン), 4.12(練習問題)1を解いてみる。

1.

やり方の1つ。(「やり方は何通りもある」(TIMTOWTDI(There Is More Than One Way To Do It.)))

コード(TextWrangler)

#!/usr/bin/env perl
use strict;
use warnings;

sub total{
  my $num = 0;
  for(@_){
    $num += $_;
  }
  return $num;
}

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

入出力結果(Terminal)

$ perl sample.pl
The total of @fred is 25.
Enter some numbers on seprate lines: 1
2
3
4
5
6
7
8
9
10
The total of those numbers is 55.
$

0 コメント:

コメントを投稿