子过程左值属性

<pre name="code" class="html">除非你定义子过程返回一个 左值,否则你你不能从子过程中返回一个可以修改的标量值:
[root@wx03 test]# cat t20.pl 
my $val;
sub canmod:lvalue  {
return $val;
}
sub nomod {
$val;
}
canmod() = 5; # 给 $val 赋值为 5
#nomod() = 5; # 错误
print "\$val is $val\n";
print "1111111111111\n";
print &canmod;
print "\n";

[root@wx03 test]# perl t20.pl 
$val is 5
1111111111111
5


修改子程序的返回值


如果你正传递参数到一个有 左值 属性的子过程,你一般会使用圆括弧来防止歧义:
[root@wx03 test]# cat t20.pl 
my $val;
sub canmod:lvalue  {
$val =shift;
return $val;
}
sub nomod {
$val;
}
canmod($x) = 100; # 给 $val 赋值为 5
#nomod() = 5; # 错误
print "\$val is $val\n";

[root@wx03 test]# perl t20.pl 
$val is 100

具有左值属性的方法调用在 不传送任何参数时也能省
略圆括弧:
$obj->canmod = 5;


12.7.6 新技巧

package Critter;
sub new {
my $class = shift;
my $self = { pups => 0, @_ }; # 覆盖缺省。
bless $self, $class;
}
sub pups : lvalue { # 我们稍后给pups()赋值
my $self = shift;
$self->{pups};
}
package main;
$varmint = Critter->new(pups => 4);
$varmint->pups *= 2; # 赋给 $varmint->pups!  这里把8赋值给$varmint->pups
$varmint->pups =~ s/(.)/$1$1/; # 现场修改 $varmint->pups!
print $varmint->pups; # 现在我们有88个pups。




[root@wx03 test]# cat t22.pl 
unshift(@INC,"/root/test"); 
use loop;
$ua=loop->new();
$str=$ua->test_fun1;
print "\$str is $str\n";
[root@wx03 test]# perl t22.pl 
ok
$str is 1


$str 是函数的返回值,这里返回1



   

posted @ 2016-05-21 15:36  czcb  阅读(119)  评论(0编辑  收藏  举报