Perl子函数参数传递

本文详细探讨了Perl中如何在子函数间传递变量,尤其是使用引用进行复杂数据结构的传递。通过实例解析了传值调用和引用传递的区别,并讲解了返回值的处理,包括整数和数据结构。
摘要由CSDN通过智能技术生成
Perl子函数参数传递

Call a subroutine and pass a variable by value

$value = "foo";

$newvalue = add_bar($value);

print "$value becomes $newvalue";

sub add_bar {

my ($copy) = @_;

$copy .= "bar";

return $copy;

}

RESULT: foo becomes foobar
DISCUSSION: In any Perl subroutine the special @_ array will always contain aliases to the variables that are passed in, so it really isn't possible to pass by value. The trap to avoid is that a subroutine which operates directly on the @_ elements will actually change the variables aliased by those elements. If you wish to operate only on the values you must copy the @_ values into local variables, operate on those local variables and then return the new result. This will leave the original variable unchanged.

Call a subroutine and pass a variable by reference

$value = "foo";

add_bar($value);

print "$value";

sub add_bar {

@_[0] .= "bar";

}

RESULT: foobar
DISCUSSION: In contrast to the previous trick this one takes advantage of Perl's default behaviour of passing aliases, to change the original variable more directly. The @_ array is sometimes described as "magical" but it is really no different from other languages which pass arguments by reference. There is no need to return the value since the original variable is directly changed as the subroutine operates on its alias.

Call a subroutine and pass a variable by reference explicitly

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值