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

Ale*_*x F 6 io perl 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
Run Code Online (Sandbox Code Playgroud)

pil*_*row 11

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

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

例如:

sub increment {
  $_[0] += 1;
}

my $i = 0;
increment($i);  # now $i == 1
Run Code Online (Sandbox Code Playgroud)

在您的"示例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...
}
Run Code Online (Sandbox Code Playgroud)