[sf-perl] & and @_

Joseph Brenner doomvox at gmail.com
Tue Feb 24 15:34:53 PST 2015


After our last gathering (with Peter Martini, at Cafe Grecco in
North Beach),  Quinn and I were talking about the quirks of
perl's argument passing, and I got something wrong that might be
worth correcting.

First of all, do y'all know what happens if you use the old perl
syntax for calling a sub?

  $result = &do_stuff;

This takes whatever might happen to be laying around in @_ and
makes it available as @_ inside of do_stuff.

The idea was that just like $_ works as a kind of singular
pronoun in perl, @_ was supposed to work as a plural pronoun.
They figured you might want to write code like this:

  sub do_stuff {
      &check_numerics;
      &discard_out_of_range;
      $sum = &total_up;
  }

And just as an aside, I think it's interesting that pretty much
none of us want to write code like that, but all of us make use
of $_ all the time.  Consistency always seems nice in theory, but
in practice it seems that different cases are often really
different...

Anyway, with the newer sub calling syntax, that automatic passing
of @_  goes away.  Without the &, if that's what you want,
you need to say it explicitly:

  my $result = do_stuff( @_ );

Quinn's question was in dealing with coderefs.
He doesn't like arrow deferencing so much:

  my $result = $code_ref->();

He falls back on the &:

  my $result = &{ $code_ref };

He was disappointed to hear that was doing something funky with
passing @_ around.

The detail that I forgot about though, is that if you've got both
an & and parenthesis in play, the parenthesis win, and that automatic
hand-off of @_ goes away.  So these cases, at least, are equivalent:

  $code_ref->( );

  &{ $code_ref }( );
  &$code_ref( );


More information about the SanFrancisco-pm mailing list