2013-05-03 34 views
1

我已經將此程序作爲初學者使用。需要澄清一些事情! 爲什麼我不能在下面給出的for循環中使用「le」,但是我可以在「if condition」中使用它。這背後的原因是什麼? ?爲什麼我們不能在for循環中使用「le」,並且可以在「if condition」中使用

print "Type the number upto series should run\n"; 
my $var; 
$var = int<STDIN>; 
chomp $var; 
my ($i, $t); 
my $x = 0; 
my $y = 1; 

if($var eq 1) { 
    print "\nYour Series is : $x\n"; 
} elsif($var eq 2){ 
    print "\nYour Series is : $x $y\n"; 
} elsif($var ge 2) { 
    print "Your Series is : $x $y "; 
    for($i = 1; $i le $var - 2; $i++) { 
     # Why the condition not working when I'm using "le" 
     # but it does work when I'm using "<=" 
     $t = $x + $y; 
     $x = $y; 
     $y = $t; 
     print "$t "; 
    } 
    print "\n"; 
} else { 
    print "Error: Enter a valid postive integer\n"; 
} 
+3

請加上'使用嚴格的;使用警告;'在(所有)腳本的頂部。 – Mat 2013-05-03 09:42:57

+0

是什麼讓你覺得這不起作用?你期望哪種行爲?你的實際結果是什麼? – innaM 2013-05-03 09:48:19

+0

我曾試過,它不能按要求工作。我也收到了其他評論。 – 2013-05-03 11:17:20

回答

3

如果您願意,您可以免費使用le<=。但是你應該知道他們完全是不同的運營商。

數字比較運算符是

== != < <= > >= <=> 

等效串對比運算符是

eq ne lt le gt ge cmp 

字符串和根據需要的數字被轉換成彼此。這意味着,例如,

3 ge 20 # true: 3 is string-greater  than 20 
11 le 2 # true: 11 is string-less-or-equal than 2 

,因爲字典順序比較字符。因此,當您想將$variables的內容作爲數字處理時,使用數字運算符是可取的,並且會產生正確的結果。

請注意,Perl不可見地在字符串和數字之間進行轉換。建議使用use warnings,以便在字符串不能表示數字時獲得有用的消息(例如"a")。

+0

非常感謝澄清事情! :)在Perl – 2013-05-03 11:21:37

1

當你比較數字與eq,le,gt .....等;他們首先被轉換爲字符串。字符串將被檢查爲字母順序,所以「11」在這裏將小於「2」。

所以你應該使用==,< =,> = ...等比較數字時。

2

已給出正確答案,ge進行字符串比較,例如11被認爲小於2。解決方案是使用數字比較,==>=

我以爲我會幫助證明你有問題。考慮默認sort是如何工作的這個示範:

$ perl -le 'print for sort 1 .. 10' 
1 
10 
2 
3 
4 
5 
6 
7 
8 
9 

正如你所看到的,它認爲比210,這是因爲字符串比較,這是sort的默認模式。這是怎樣的默認引擎蓋下排序例程的外觀:

sort { $a cmp $b } 

cmp屬於字符串比較運營商,像eqlege。這些運營商被描述爲herecmp低於此)。

對於排序規則來辦,我們期待在上面的例子是什麼,我們將不得不使用數值比較運營商,這是「太空飛船操作」 <=>

sort { $a <=> $b } 

在你的情況,你可以試試你的問題與這一個班輪:

$ perl -nlwe 'print $_ ge 2 ? "Greater or equal" : "Lesser"' 
1 
Lesser 
2 
Greater or equal 
3 
Greater or equal 
11 
Lesser 
+0

謝謝:)作爲初學者我還在學習的東西。 – 2013-05-03 11:19:38

1

我想你可能希望看到產生Fibonnaci系列像你更類似Perl程序。

use strict; 
use warnings; 

print "Type the length of the series\n"; 
chomp(my $length = <>); 
unless ($length and $length !~ /\D/ and $length > 0) { 
    print "Error: Enter a positive integer\n"; 
} 

print "\n"; 

my @series = (0, 1); 
while (@series < $length) { 
    push @series, $series[-2] + $series[-1]; 
} 

print "@series[0..$length-1]\n"; 
相關問題