Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I am a little confused with perl subroutines. Can anybody explains the differences in ways to call subroutines for me.

sub Test { my ($X,$Y) = @_; return "Hello $X and $Y\n"; } print "With &\n"; print &Test('name 1','name 2'); print "Without &\n"; print Test('name 1','name 2'); print "Without brackets\n"; print Test 'name 1','name 2';
what is the best practice to use, when and why?
Thanks in advance

Replies are listed 'Best First'.
Re: Perl Subroutines Call
by ph0enix (Friar) on Jan 05, 2010 at 11:07 UTC

    From perlsub. To call subroutines:

    1. NAME(LIST); # & is optional with parentheses. 2. NAME LIST; # Parentheses optional if predeclared/imported. 3. &NAME(LIST); # Circumvent prototypes. 4. &NAME; # Makes current @_ visible to called subroutine.

    Personaly I prefer to use NAME(LIST); and prefix & only in special cases like &$code.

Re: Perl Subroutines Call
by herveus (Prior) on Jan 05, 2010 at 12:38 UTC

    Don't use the & form unless you require it's special effects. If you don't know what those are, you don't need them. I'm not trying to be snarky or a wiseass.

    I normally use parentheses around the arguments, in part just to make it clear what is being passed to the subroutine. At times, I omit them, but I can't really articulate the conditions that apply. I suppose aesthetics bear on the decision, but I tend to "err" on the side of ().

Re: Perl Subroutines Call
by amir_e_a (Hermit) on Jan 05, 2010 at 15:53 UTC

    This one is the best option:

    print Test('name 1','name 2');

    Even better, with a space after a comma:

    print Test('name 1', 'name 2');

    The & is not needed. It's old-fashioned and may have side effects, which aren't too interesting.

    The parentheses make the code more readable.

    Damian Conway in "Perl Best Practices" suggests always using parentheses with subroutines and no parentheses with builtins such as print, unpack etc. If you don't have the book, you may see the relevant excerpt at its Amazon page.