develooper Front page | perl.beginners | Postings from May 2007

Re: Passing arguments to subroutine

Thread Previous | Thread Next
Chas Owens
May 31, 2007 06:40
Re: Passing arguments to subroutine
Message ID:
On 31 May 2007 01:27:26 -0700, Alma <> wrote:
>         &deleteposter_file(@row);
> sub delete_file()

This would seem to be the problem, also where did you learn that you
should put & on the front of your subroutine calls?  I am curious
because I keep seeing people do it without understanding what it is
for.  Way back, in the dawn of time, it was the way to call
subroutines, but it then it changed to just

from perldoc perlsub
        To call subroutines:

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

Note the extra bits that happen when you call it with &?  They can be
handy when you expect them and trying to achieve a specific effect,
but they can cause problems for the unwary:


use strict;
use warnings;

sub i_have_a_prototype($$$) {
        print "I can only be called with three parameters,",
                "they are $_[0], $_[1], and $_[2]\n"

eval qq{ i_have_a_prototype(1);       } or print "$@\n";
eval qq{ i_have_a_prototype(1, 2);    } or print "$@\n";
i_have_a_prototype(1, 2, 3);
&i_have_a_prototype(6); #oops



use strict;
use warnings;

sub outer {
        if ($_[0] eq 'none') {
        } else {
                &inner("arg1", "arg2");

#this is not treadsafe, but the first call
#sets up foobar, and all subsequent calls
#use foobar
sub inner {
        if (@_ == 0) {
                print "no args, so setup foobar\n";

        #if we get here then args were passed
        #and foobar should setup
        local $" = ", ";
        print "I was call like this inner(@_)\n";

outer('none'); #setup foobar
outer('use');  #use foobar

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About