#title Perl 特殊变量
大概像这样:
<src lang="perl">
foreach ( qw(a.txt b.txt) ) {
test($_);
}
sub test {
my $file = shift;
open(FH, $file) || die "Cann't open file $file: $!";
$i = 1;
while (<FH>) {
print $_;
last if $i++ > 10;
}
}
</src>
错误提示说:
<example>
perl "e:/Programs/emacs/home/temp/t.pl"
Modification of a read-only value attempted at e:/Programs/emacs/home/temp/t.pl line 36.
</example>
后来终于知道怎么回事了,在 foreach 那里 $_ 被赋值成一个字符常量,
由于 $_ 是全局变量,所以在函数中仍然是一个字符常量,这样 <FH> 就不能
赋值给 $_ 了。
结论是:使用 $_ 要很小心。还是显示的声明比较好。
转 Python Humor 中的一首诗:
<example>
The Zen of Python (by Tim Peters)
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
</example>