開発環境
- OS X Lion - Apple(OS)
- TextWrangler(Text Editor) (BBEditの機能制限無料版、light版)
- Script言語:Perl
『初めてのPerl 第6版』(Randal L. Schwartz, Tom Phoenix, brian d foy 共著、近藤 嘉雪 訳、オライリー・ジャパン、2012年、ISBN978-4-87311-567-2)の4章(サブルーチン)、4.12(練習問題)4を解いてみる。
その他参考書籍
4.
コード(BBEdit)
sample.pl
#!/usr/bin/env perl
use strict;
use warnings;
use utf8;
use 5.016;
binmode STDOUT, ':utf8';
binmode STDIN, ':utf8';
sub greet {
my $name = shift;
state $last;
if ($last) {
print "Hi ${name}! $last is also here!\n";
} else {
print "Hi ${name}! You are the first one here!\n";
}
$last = $name;
}
greet( "Fred" );
greet( "Barney" );
入出力結果(Terminal)
$ ./sample.pl Hi Fred! You are the first one here! Hi Barney! Fred is also here! $
ちなみにJavaScriptの場合。
コード(BBEdit)
$('#pre0').text("");
// JavaScriptで同様の事を実現する場合はクロージャーっていうのを使えばいいのかな。。
// (Perlではクロージャ使ってないけど)
var greet = (function () {
var last;
return function(name) {
if (last) {
$('#pre0').append("Hi " + name + "! " + last + " is also here!\n");
} else {
$('#pre0').append("Hi " + name + "! You are the first one here!\n");
}
last = name;
};
})(),
names = ["Fred", "Barney", "Python", "JavaScript", "HTML5"],
i, max;
for (i = 0, max = names.length; i < max; i += 1) {
greet(names[i]);
}
pythonの場合。
コード(BBEdit)
sample.py
#!/usr/bin/env python3.3
#-*- coding: utf-8 -*-
# ステート情報を保存するのはクラスの方がいいかなあと思ったので
class C:
last = None
def greet(self, name):
if C.last:
print("Hi {0}! {1} is also here!".format(name, C.last))
else:
print("Hi {0}! You are the first one here!".format(name))
C.last = name
c = C()
for name in ["Fred", "Barney", "Python", "JavaScript", "HTML5"]:
c.greet( name )
入出力結果(Terminal)
$ ./sample.py Hi Fred! You are the first one here! Hi Barney! Fred is also here! Hi Python! Barney is also here! Hi JavaScript! Python is also here! Hi HTML5! JavaScript is also here! $
0 コメント:
コメントを投稿