2013年7月8日月曜日

開発環境

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

その他参考書籍

1.

コード(BBEdit)

sample.pl

#!/usr/bin/env perl
use strict;
use warnings;
use 5.016;
use utf8;
binmode STDOUT, ':utf8';
binmode STDIN, ':utf8';

sub total {
    my $result = 0;
    for  (@_) {
        $result += $_;
    }
    $result;
}
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 seqarate lines: ";
my $user_total = total(<STDIN>);
print "The total of those numbers is $user_total.\n";

入出力結果(Terminal)

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

ちなみにpython3.3の場合。

コード(BBEdit)

sample.py

#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-

spam = [1, 3, 5, 7, 9]

def total(a):
    res = 0
    for n in a:
        res += n
    return res

spam_total = total(spam)
print("The total of spam is {0}.".format(spam_total))

print("Enter some numbers on separate lines: ")
user_numbers = []
while True:
    n = input()
    if n == "":
        break
    user_numbers.append(float(n))

user_total = total(user_numbers)
print("The total of those numbers is {0:g}".format(user_total))

入出力結果(Terminal)

$ ./sample.py
The total of spam 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
$

0 コメント:

コメントを投稿