perl read()函数和缓冲区背后的魔力是什么?

时间:2010-06-10 04:33:56

标签: perl io buffer handle

我无法理解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

2 个答案:

答案 0 :(得分:11)

不需要魔法 - 如果你愿意,所有perl子程序都是别名调用。 Quoth perlsub

  

数组@_是一个本地数组,但它的元素是别名   对于实际的标量参数。特别是,如果元素$ _ [0]   更新后,相应的参数将更新(或发生错误   如果它不可更新)。

例如:

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...
}

答案 1 :(得分:0)

read()是一个内置函数,所以可以做魔术。但是,通过声明function prototype

,您可以使用自己的函数完成类似的操作
sub myread(\$) { ... }

参数声明\$表示该参数被隐式传递为参考。

内置read中唯一的魔力就是它可以间接调用或作为文件句柄方法工作,这对常规函数不起作用。