一段小程序(Perl vs. Ruby)
讀《Perl語言入門》(第四版,我買的書,網上有個翻譯質量很高的電子版)的第10章的習題,人見人愛的猜數遊戲,用perl寫出來大概這樣:
$num=int (1 + rand 100);
print "I have a number,guess it?:\n";
while(<>)
{
chomp;
next unless /\d+/;
$_>$num? print "Too high\n" :
$_==$num? last :print "Too low\n";
}
題外話:玩Perl的高人們別鄙視我,我是perl新手啊,如果寫的不夠“perl”,多多指點。print "I have a number,guess it?:\n";
while(<>)
{
chomp;
next unless /\d+/;
$_>$num? print "Too high\n" :
$_==$num? last :print "Too low\n";
}
這段代碼轉成ruby,可以這樣寫:
$num=1+(rand 100)
puts "I have a number guess it?"
while(true)
gets.chomp
next unless ~/\d+/
$_.to_i>$num?begin print "Too high\n" end:
$_.to_i==$num? begin break end:begin print "Too low\n" end
end
puts "I have a number guess it?"
while(true)
gets.chomp
next unless ~/\d+/
$_.to_i>$num?begin print "Too high\n" end:
$_.to_i==$num? begin break end:begin print "Too low\n" end
end
看出來了吧,兩者何其相似啊,包括perl裏麵人見人愛的$_,ruby也是支持的,唯一那麼一點不同的地方就是last換成了break,然後是正則表達式左邊多了個~,你完全可以將這個符號去掉,不過會有警告,最後就是Ruby中的要執行的表達式得放在begin...end裏麵,這一點讓我琢磨了一段時間,還以為Ruby不支持呢。讀《Perl語言入門》最大的樂趣除了妙趣橫生的語言、古靈精怪的符號之外,就是尋找Ruby中的Perl痕跡,哦哦,那個味道相當重——駱駝的味道。不過現在Ruby不鼓勵這樣的寫法,畢竟,程序是給人讀的,因此可以改寫一下:
$num=1+(rand 100)
puts "I have a number guess it?"
while(true)
guess=STDIN.gets
next unless guess=~/\d+/
if(guess.to_i>$num)
puts "Too high"
elsif(guess.to_i==$num)
break
else
puts "Too low"
end
end
puts "I have a number guess it?"
while(true)
guess=STDIN.gets
next unless guess=~/\d+/
if(guess.to_i>$num)
puts "Too high"
elsif(guess.to_i==$num)
break
else
puts "Too low"
end
end
文章轉自莊周夢蝶 ,原文發布時間2007-12-07
最後更新:2017-05-17 17:01:56