开发者

Is $return variable anyhow special in Perl?

开发者 https://www.devze.com 2023-03-08 01:41 出处:网络
We have observed strange effects when using $return variable in code 开发者_StackOverflow社区like $return = foo($something);. Is $return variable somehow special because of the return name?According t

We have observed strange effects when using $return variable in code 开发者_StackOverflow社区like $return = foo($something);. Is $return variable somehow special because of the return name?


According to the Perl documentation, no.


No it is not perl special. But some module my export it and this may provide unexpected behavior.

see This tutorial


There's nothing special about a variable named $return. That said, writing

my $return = foo($something);
return $return;

is not the same as writing

return foo($something);

The first form puts the call to foo() in scalar context. The latter will propagate the context from the caller. This could cause foo() to behave differently. Compare:

sub foo { return localtime }
sub bar { my $x = foo(); return $x }
sub baz { return foo() }

say join ', ', bar(); # Thu May 26 08:24:59 2011
say join ', ', baz(); # 59, 24, 8, 26, 4, 111, 4, 145, 1

This happens because in scalar context, localtime returns the time formatted as a string but in list context it returns a list of values for seconds, minutes, hours, etc.

The concept of context is unique to Perl. To learn more about it, see perlsub.

0

精彩评论

暂无评论...
验证码 换一张
取 消