[sf-perl] & and @_

Quinn Weaver quinn at pgexperts.com
Thu Feb 26 12:28:14 PST 2015

> On February 24, 2015, at 3:34 PM, Joseph Brenner <doomvox at gmail.com> wrote:
> […]

> 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...

True! Even if I had known about this idiom, I was passing objects
(or calling methods on them), which I suppose is just a different
way of passing everything in to the called sub.

Anyway, if I wanted to pass @_ I'd do it explicitly, because otherwise
&code; looks, to someone unaware of these details, like an invocation
with zero args. "Explicit is better than implicit." Oh hey, the Python
I'm writing lately must be rubbing off on me. :)

> 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 };

Actually, I preferred

&$coderef($foo, $bar);

But I've since accepted that the arrow notation is more widely

The reason I liked it, I think, is that back then I always used &
to call subroutines, so it seemed consistent. Also, I was accustomed
to dereferencing %$hashrefs and @$arrayrefs without brackets
(this was before Perl Best Practices).

It's weird to think that, while some people hop from language to
language, in Perl you can hop from style to style *within the language*.

> 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.

Yeah, using parentheses for everything (except builtin functions)
is my convention now (again, PBP).

>  So these cases, at least, are equivalent:
>  $code_ref->( );
>  &{ $code_ref }( );
>  &$code_ref( );

Thanks for following up on this!

Quinn Weaver
PostgreSQL Experts, Inc.
1-888-743-9778 (my extension: 510)

More information about the SanFrancisco-pm mailing list