What is the right way to call a function stored in a variable?
my $f = sub () { ... };
&$f(); # 1st
$f->(); # 2nd
Both appear to work, and the first probably worked in perl4.
However, I was wondering what the “official perl5 way” was.
Also, are there any performance implications?
Both are the right way. Perl is not about forcing any special style down your throat.
Style #1
&$f()Pro:
Con:
Caveats:
In the dark ages of perl4, there were no references. One could simulate references by passing around variable names (*shudder*). This also works with subs, so this code runs:
Please
use strict 'refs'to guard against this horror.Style #2
$f->()Pro:
Con:
Caveats:
Same as with the other syntax, as they are the same under the hood. But the dereference operator is not misused as often.
Performance implications
Lets face it, if we were all about performance, we would be writing assembler. If you want to optimize Perl, first optimize the algorithm, then code everything in C/XS, throw away any objects and modules, and finally discuss dereferencing syntax.
I would guess style #1 is faster in theory, but I doubt it would have serious implications in real life.