1

Every now and then I see Perl scripts where subroutines are called with a leading '&'. Is this legacy, or does it give any benefit? As calling the subroutine without the ampersand sign works as well.

sub mysub {
        print "mysub\n"; 

}

mysub;
&mysub;

Thx/Hermann

user2050516
  • 760
  • 2
  • 5
  • 15
  • 1
    http://perldoc.perl.org/perlfaq7.html#What's-the-difference-between-calling-a-function-as-%26foo-and-foo()%3f – fugu Feb 20 '14 at 12:57
  • @Quentin I think you're referring to [goto](http://perldoc.perl.org/functions/goto.html). – mpapec Feb 20 '14 at 13:12

1 Answers1

4

Calling with & is generally a code smell that somebody doesn't know what they're doing and are in a Perl4 mindset. In your specific example, it works exactly the same. However, calling with & disables function prototypes, so advanced users may use it in certain circumstances. You should expect to see a comment why next to the call in that case.

pndc
  • 3,710
  • 2
  • 23
  • 34
  • 4
    *Perl4 mindset.* possibly aquired by learning by googling and picking up bad examples – justintime Feb 20 '14 at 13:02
  • Thanks a lot it is clear to me now. In my particular case the real subroutine had a prototype or even empty prototype (don't know how to say): sub mysub() { ... }. That works only if you disable function prototypes with &. – user2050516 Feb 20 '14 at 13:14
  • See the parenthesis next to mysub(). Calling this subroutine with () prototype works only if you disable function prototypes with & like &mysub; – user2050516 Feb 20 '14 at 13:22
  • 1
    Actually, `mysub;` and `&mysub;` are not exactly the same. The latter is equivalent to `&mysub(@_)`, not `&mysub()`. – tobyink Feb 20 '14 at 23:20