2014-10-31 95 views
1

我無法用Perl做出是/否的問題,而我只是無法弄清楚。我很喜歡這個。如果遇到麻煩Perl語句

#! usr/bin/perl 

print "Hello there!\n"; 
print "What is your favorite game?\n"; 
$name = <STDIN>; 
chomp $name; 
print "That's awesome! $name is my favorite game too!\n"; 

print "Do you think this is a fun script (Y/n) \n"; 
$status = <STDIN>; 
if [ $status = "y" ]: then 

print "YAY! I knew you would like it!\n"; 

if [ $status = "n" ]: then 

print "You suck, not me!\n"; 

我在做什麼錯?

+1

如果Perl語句不使用方括號來包含條件,則它們使用括號。他們也不使用'then'關鍵字。 'if($ status eq'y'){} elsif {} else {}' – 2014-10-31 20:48:07

回答

4

if [是一個shell語法。在Perl中,您應該使用

if (...) { 

另外,=是賦值運算符。對於字符串平等,使用eq

if ($status eq 'y') { 
    print "YAY\n"; 

前相比,你應該chomp $狀態以同樣的方式你已經咬食$名稱。

另外,請注意Yy不相等。

而且,你的第一個(「家當」)線錯過起始斜線:

#! /usr/bin/perl 
+0

就像我說的,我是一個noob。 – 2014-10-31 20:59:03

+0

@ysth:謝謝,更新。 – choroba 2014-10-31 21:52:28

2
if [ $status = "y" ]: then 

這是Bourne(或bash)shell語法。等效的Perl代碼是:

if ($status eq "y") { 
    # ... 
} 

eq是字符串的等同比較; ==比較數字。

(你做錯了,是不包括在你的問題的錯誤消息的另一件事。)

例如:

$status = <STDIN>; 
chomp $status; 
if ($status eq "y") { 
    print "YAY! I knew you would like it!\n"; 
} 

還有一些其他的事情可以做,以提高你的Perl碼。例如,你應該始終有:

use strict; 
use warnings; 

附近的源文件的頂部(這將需要聲明的變量,可能與my)。我建議先讓這個程序開始工作,然後再擔心這個問題,但這絕對是您長期想要做的事情。

+0

你能給我一個我的代碼示例_with_你的解決方案嗎?我試圖修復它,但它顯示了兩個響應,而不是僅僅是預期的響應。 – 2014-10-31 21:10:11

+0

@StrategyFirst:查看我更新的答案。 – 2014-10-31 21:13:38

1

首先,一如既往,始終把use strict;use warnings;在你的程序的頂部。這將捕捉各種錯誤,如在if語句中使用==設置變量的值。 ==測試數字相等,eq測試字符串相等。

這是您的程序重寫。第一行#!在PATH中搜索可執行的Perl。這樣,您不必擔心Perl是在/usr/bin/perl還是/bin/perl/usr/local/bin/perl

#! /usr/bin/env perl 
use strict; 
use warnings; 
use feature qw(say); # Allows the use of the "say" command 

say "Hello there!"; 
print "What is your favorite game? "; 
my $name = <STDIN>; 
chomp $name; 
say "That's awesome! $name is my favorite game too!"; 

print "Do you think this is a fun script (Y/n) \n"; 
my $status = <STDIN>; 
chomp $status; 
if ($status eq "y") { 
    say "Yay! I knew you would like it!"; 
} 
elsif ($status eq "n") { 
    say "You suck, not me!"; 
} 

一個更好的辦法可能是檢查輸入是否開始與y與否:

if ($status =~ /^y/i) { # Did it start with a 'y' or 'Y'? 
    say "Yay! I knew you would like it!"; 
else { 
    say "You suck, not me!"; 
} 

注意使用my聲明變量。這是use strict;需要的東西,並會遇到很多編程錯誤。請注意,sayprint相似,但我不必將\n放在最後。

+0

非常有幫助!我很欣賞你經歷過的所有麻煩。 :) – 2014-10-31 21:25:26

+0

@ysth - 哎呀!糾正。 – 2014-11-13 15:07:40

+0

@ysth我實際上更喜歡使用'chomp(my $ var = );'。一遍又一遍地使用這個語法使得我使用的語法_natural_,並且我永遠不會忘記在讀取時使用'chomp'。然而,這可能會讓人感到困惑,所以我傾向於在這裏使用單獨的「chomp」。 – 2014-11-13 15:12:47