http://www.perlmonks.org?node_id=207610

@rocks has asked for the wisdom of the Perl Monks concerning the following question:

Hi Perl Monks,

I just wanted to get something straight that I read in Learning Perl 3rd Edition. I am on Chapter 4 Subroutines. I am wondering if after you define a subroutine with the & character that I can just say sub then the subroutine. For example can I....

&max { if ($a=$b){ print "hey!, that's the same thing./n"; } else { print "those aren't the same things.\n";
and then after I have defined that subroutine can I run it later in the script by just saying....

sub max that is my question. Can I? Also, if you have any extra time please tell me what it mean when you can "omit the ampersand" when using subroutines. Is it like I said when you say "Sub max", or something totally different?

-@rocks

Replies are listed 'Best First'.
Re: Defining Subroutines
by Zaxo (Archbishop) on Oct 24, 2002 at 03:02 UTC

    You got it backwards. Define a function with sub. You can call it with &max, but it's better to call using parentheses until you're comfortable with what the ampersand does. It causes prototypes to be ignored, and it arranges for the function to be called with the existing @_ as arguments.

    After Compline,
    Zaxo

      Not quite, using the ampersand causes the routine call to use the existing @_ as the default arguments. If you provide arguments they are used instead.
      sub z { my $i =1; foreach (@_) { print "$i : $_\n"; $i++; } } sub x { &z; # 1 &z( "good", "bye"); &z; # same as one again &z(); # called with empty list } x( "say", "hello");
      Ok Zaxo, Thank you very much for the information. I got it now, thank you.

      -@rocks

Re: Defining Subroutines
by janx (Monk) on Oct 24, 2002 at 06:58 UTC
    Watch out for that comparison you do!
    $a = $b; # assigns the value of $b to $a $a == $b; # compares the two numerically
    Note that your code won't fail compiling (aside from the already answered sub issues ;-)) but it won't do what you expect it would.

    janx