Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Perl Subroutines Call

by Anonymous Monk
on Jan 05, 2010 at 10:04 UTC ( [id://815725]=perlquestion: print w/replies, xml ) Need Help??

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

Hi,
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
    Howdy!

    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 ().

    yours,
    Michael
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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://815725]
Approved by zwon
Front-paged by zwon
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (4)
As of 2024-04-18 20:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found