Is there a difference between & $ func ($ arg) and $ func & # 8594; ($ arg)?

When trying to understand closure, reading through perl-faq and coderefin perlref found the following examples:

sub add_function_generator {
    return sub { shift() + shift() };
}
my $add_sub = add_function_generator();
my $sum = $add_sub->(4,5);

and

sub newprint {
    my $x = shift;
    return sub { my $y = shift; print "$x, $y!\n"; };
}
$h = newprint("Howdy");
&$h("world");

here are two forms of calling a function stored in a variable.

&$func($arg)
$func->($arg)

Are these completely equivalent (only syntactically different) or are there some differences?

+4
source share
1 answer

There is no difference. Proof: opcodes generated by each version:

$ perl -MO=Concise -e'my $func; $func->()'
8  <@> leave[1 ref] vKP/REFC ->(end)
1     <0> enter ->2
2     <;> nextstate(main 1 -e:1) v:{ ->3
3     <0> padsv[$func:1,2] vM/LVINTRO ->4
4     <;> nextstate(main 2 -e:1) v:{ ->5
7     <1> entersub[t2] vKS/TARG ->8
-        <1> ex-list K ->7
5           <0> pushmark s ->6           
-           <1> ex-rv2cv K ->-           
6              <0> padsv[$func:1,2] s ->7
$ perl -MO=Concise -e'my $func; &$func()'
8  <@> leave[1 ref] vKP/REFC ->(end)     
1     <0> enter ->2                      
2     <;> nextstate(main 1 -e:1) v:{ ->3 
3     <0> padsv[$func:1,2] vM/LVINTRO ->4
4     <;> nextstate(main 2 -e:1) v:{ ->5 
7     <1> entersub[t2] vKS/TARG ->8      
-        <1> ex-list K ->7               
5           <0> pushmark s ->6           
-           <1> ex-rv2cv sKPRMS/4 ->-    
6              <0> padsv[$func:1,2] s ->7

... wait, - <1> ex-rv2cv sKPRMS/4 ->-there are slight differences in the flags for . In any case, they do not seem important, and both forms behave the same.

$func->(): , parens (&$func , @_ , , ).

+13

All Articles