TOP

Perl bits: Passing @_ to a subroutine

Perl subroutines may be called with or without leading & and with or without () at the end. Either one is strongly recommended – the command might end up as something else than a function call if both are missing.

I just discovered a nice Perl trick which bothered be years ago:

&foo
is different from
&foo()

The first gets access to the global @_ (aka whatever function foo was called
from, its @_ is handed to foo), the latter does not.

Simply:

sub a { &b; }
sub b { print $_[0]; }
a("Hello World");

It works!

But this is unexpeced (usually) as few cases require silent argument passing. I switched to the b() form for every function call to be safe from unexpected parameter inheritance.

Maybe I’ll use the &b form (with a comment explaining why it’s used) when I need to pass a huge arguments on to the next called sub – it should be much faster to let the called sub also use the same @_ instead of creating a new copy for it.

Yor might even manipulate the parents @_ this way… no, better don’t think about it, the result would be un-maintainable source.

3 Kommentare. Schreib was dazu

  1. hehe, gerade heute zufällig ein Script geschrieben, was das verhalten nutzt:

    while () {
    chomp; next unless $_;
    @_ = split /s/;
    push @_, ++$p;
    &create_vhost
    }

  2. hehe, gerade heute zufällig ein Script geschrieben, was das verhalten nutzt:

    while () {
    chomp; next unless $_;
    @_ = split /s/;
    push @_, ++$p;
    &create_vhost
    }

  3. hehe, gerade heute zufällig ein Script geschrieben, was das verhalten nutzt:

    while () {
    chomp; next unless $_;
    @_ = split /s/;
    push @_, ++$p;
    &create_vhost
    }

Schreib was dazu

Your email is never published nor shared.

You may use these HTML tags and attributes:<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

eMail-Benachrichtigung bei weiteren Kommentaren.
Auch möglich: Abo ohne Kommentar.