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

前端之家收集整理的这篇文章主要介绍了perl read()函数和缓冲区背后的魔力是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我不明白Perl read($buf)函数如何能够修改$buf变量的内容. $buf不是引用,因此参数由copy(来自我的c / c知识)给出.那么为什么在调用者中修改$buf变量呢?

它是一个平局变量还是什么?关于setbuf的C文档对我来说也是非常难以理解的

  1. # Example 1
  2. $buf=''; # It is a scalar,not a ref
  3. $bytes = $fh->read($buf);
  4. print $buf; # $buf was modified,what is the magic ?
  5.  
  6. # Example 2
  7. sub read_it {
  8. my $buf = shift;
  9. return $fh->read($buf);
  10. }
  11. my $buf;
  12. $bytes = read_it($buf);
  13. 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).

例如:

  1. sub increment {
  2. $_[0] += 1;
  3. }
  4.  
  5. my $i = 0;
  6. increment($i); # now $i == 1

在“示例2”中,read_it子将@_的第一个元素复制到词法$buf,然后通过调用read()“复位”该副本.传入$_ [0]而不是复制,看看会发生什么:

  1. sub read_this {
  2. $fh->read($_[0]); # will modify caller's variable
  3. }
  4. sub read_that {
  5. $fh->read(shift); # so will this...
  6. }

猜你在找的Perl相关文章