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

Re: Passing arguments to subroutine

Thread Previous | Thread Next
From:
Chas Owens
Date:
May 31, 2007 06:40
Subject:
Re: Passing arguments to subroutine
Message ID:
58ce48dc0705310636x29b69003k5f96da7bd2d8f280@mail.gmail.com
On 31 May 2007 01:27:26 -0700, Alma <almatirkey@gmail.com> wrote:
snip
>         &deleteposter_file(@row);
snip
> sub delete_file()
snip

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
"deleteposter_file(@row);".

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:

#!/usr/bin/perl

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

Also

#!/usr/bin/perl

use strict;
use warnings;

sub outer {
        if ($_[0] eq 'none') {
                &inner;
        } 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";
                return;
        }

        #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


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About