剛剛才知道perl的foreach…
我剛剛才知道perl的foreach和for會有些差別
像是這樣一段:
my $tn;
foreach $tn (0..$#templates){
last if ($templates[$tn] eq $new_template);
}
print $tn;
就是要在 @templates裡面找出有沒有和 $template相同的字串, 但是用last跳出foreach迴圈後, 不論是不是有找到都不會印出東西, 其實Programming Perl裡面有解釋:
The loop variable is valid only from within the dynamic or lexical scope of the loop and will be implicitly lexical if the variable was previously declared with my. This renders it invisible to any function defined outside the lexical scope of the variable, even if called from within that loop. However, if no lexical declaration is in scope, the loop variable will be a localized (dynamically scoped) global variable; this allows functions called from within the loop to access that variable. In either case, any previous value the localized variable had before the loop will be restored automatically upon loop exit.
總之就是那個loop variable外面拿不到就對了, 但是如果有use strict的話, 不宣告$tn就不能跑, 那在迴圈外的$tn是宣告來心酸的就是了…所以要在外面拿到$tn的話必須要這樣子做:
my $tn;
for($tn=0;$tn< =$#templates;$tn++){
last if ($templates[$tn] eq $new_template);
}
print $tn;
總之今天才知道foreach和for的差別……
註: 我用的是Windows上的ActivePerl 5.8.8 Build 817
有 use strict 的話不宣告 $tn 就不能跑,不過 $tn 可以宣告在 foreach 裡面:
foreach my $tn (0..$#templates) { ..... }
比較短的寫法:
(不過比較浪費時間,不像 for 迴圈一找到就馬上跳出來)
my ($tn) = grep { $_ eq $new_template } @templates;
print $tn;
Comment by salagadoola — June 20, 2006 @ 11:04 am