in reply to subroutine / dot operator / hash vlaue
G'day starfire4444,
Welcome to the Monastery.
When you call a subroutine with a leading '&', you are specifying that you wish to ignore whatever prototype you used in the subroutine definition. Did you use a prototype? If so, do you want to ignore it?
In almost all cases, the answer to first question is NO: consequently, the second conditional question is not applicable. Unless you know exactly what you're doing, and are able to explain with unerring clarity why you're doing it, never call a subroutine with a leading ampersand.
At this point, it may be useful to read the SYNOPSIS of perlsub.
I strongly suspect that your definition of get_value2 does not include a prototype. If it does, you need to show it. If it doesn't, adding an ampersand makes no difference; however, its presence suggests that a prototype was involved: be wary of angry maintenance programmers with clenched fists; read about hubris in perlglossary.
Now, let's just take this one step at a time:
Printing the return value directly:
$ perl -wE 'sub f { 42 } say f()' 42 $ perl -wE 'sub f { 42 } say &f()' 42
Saving the return value and then printing:
$ perl -wE 'sub f { 42 } my $x = f(); say $x' 42 $ perl -wE 'sub f { 42 } my $x = &f(); say $x' 42
Saving a reference to the return value and then printing:
$ perl -wE 'sub f { 42 } my $x = \f(); say $x' SCALAR(0x7fc8f2805480) $ perl -wE 'sub f { 42 } my $x = \&f(); say $x' SCALAR(0x7f9783805480)
Saving a reference to the return value and then printing the dereferenced return value:
$ perl -wE 'sub f { 42 } my $x = \f(); say $$x' 42 $ perl -wE 'sub f { 42 } my $x = \&f(); say $$x' 42
As I hope you can now see, adding an ampersand when calling a subroutine, which was defined without a prototype, serves no purpose whatsoever other than to appease whomsoever personifies Confusion in whatever mythos you subscribe to.
[Aside: What you're referring to as the dot operator is, in fact, the string concatenation operator: see "perlop: Additive Operators".]
— Ken
|
|---|