2013年2月25日月曜日

開発環境

『初めての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 utf8;
use 5.016;
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 seprate 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 seprate lines: 1
2
3
4
5
6
7
8
9
10
The total of those numbers is 55.
$

ちなみにJavaScriptの場合。

コード(BBEdit)

var nums = [1,3,5,7,9],
    total = function( nums ) {
        var result = 0,
            i, max;
        for (i = 0, max = nums.length; i < max; i += 1) {
            result += nums[i];
        }
        return result;
    };
$('#pre0').text(total(nums));



pythonの場合。

コード(BBEdit)

sample.py

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

def total(nums):
    result = 0
    for x in nums:
        result += x
    return result

nums = [1, 3, 5, 7, 9]
print(total(nums))

入出力結果(Terminal)

$ ./sample.py
25
$

0 コメント:

コメントを投稿