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

前端之家收集整理的这篇文章主要介绍了perl read()函数和缓冲区背后的魔力是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我不明白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...
}
原文链接:https://www.f2er.com/Perl/171420.html

猜你在找的Perl相关文章