我不明白Perl read($buf)函数如何能够修改$buf变量的内容. $buf不是引用,因此参数由copy(来自我的c / c知识)给出.那么为什么在调用者中修改$buf变量呢?
它是一个平局变量还是什么?关于setbuf的C文档对我来说也是非常难以理解的
# Example 1 $buf=''; # It is a scalar,not a ref $bytes = $fh->read($buf); print $buf; # $buf was modified,what is the magic ? # Example 2 sub read_it { my $buf = shift; return $fh->read($buf); } my $buf; $bytes = read_it($buf); print $buf; # As expected,this scope $buf was not modified
解决方法
不需要魔法 – 所有perl子程序都是别名调用,如果你愿意的话.第
perlsub号:
The array @_ is a local array,but its elements are aliases
for the actual scalar parameters. In particular,if an element $_[0]
is updated,the corresponding argument is updated (or an error occurs
if it is not updatable).
例如:
sub increment { $_[0] += 1; } my $i = 0; increment($i); # now $i == 1
在“示例2”中,read_it子将@_的第一个元素复制到词法$buf,然后通过调用read()“复位”该副本.传入$_ [0]而不是复制,看看会发生什么:
sub read_this { $fh->read($_[0]); # will modify caller's variable } sub read_that { $fh->read(shift); # so will this... }