[Edinburgh-pm] Parameter passing, seeking an answer....

Aaron Crane perl at aaroncrane.co.uk
Thu Sep 6 02:26:53 PDT 2007


Ian Stuart writes:
> sub myFunc {
>   my self = shift;
> }
> 
> sub myFunc {
>    my ($self) = @_;
> }
> 
> Is there a good compelling reason for this (new to me) style?

Unpacking @_ with a direct list assignment is more concise, and
collecting several arguments in a horizontal list tends to make your
code more readable.  (As long as the list isn't too long, anyway, but
in that case, you probably want to refactor your function so that it
doesn't take so many positional arguments.)

The list-assignment approach also lets your argument-unpacking code
visually mimic the calling syntax.

Here's an example from a piece of code I happen to have open right
now.  The list-assignment version

  sub set_teasers {
      my ($db, $slot_id, $contents) = @_;
      # ...
  }

is much more concise (and, I believe, more readable) than

  sub set_teasers {
      my $db       = shift;
      my $slot_id  = shift;
      my $contents = shift;
      # ...
  }

In particular, this form of concision saves screen lines.  That's
particularly valuable given that screen lines are one of the few
non-renewable resources we have: as screens get physically larger, you
have to put them further away from your eyes to be able to see the
whole screen comfortably, so there's a hard limit on the number of
lines you can see at once.

Some people prefer to use shift for method invocants, but unpack other
arguments with a single list assignment:

  sub send {
      my $self = shift;
      my ($sender, $recipient, $message) = @_;
      # ...
  }

That makes the method definition reflect the calling syntax, in which
the invocant is separated from the other arguments:

  $smtp->send($sender, $recipient, $message)

But you still have to pay for that by spending an extra line on merely
unpacking your parameters.

Damian Conway recommends ("Perl Best Practices", O'Reilly, 2005)
using shift to unpack arguments in situations where "one or more of
them has to be sanity-checked, or needs to be documented with a
trailing comment", and offers this example:

  sub padded {
      my $text           = _check_non_empty(shift);
      my $cols_count     = _limit_to_positive(shift);
      my $want_centering = shift;
      # ...
  }

As with all stylistic questions, though, the most important thing is
consistency across a single codebase: if your team has agreed on one
particular style, then adopting that style makes the whole codebase
easier to read.

-- 
Aaron Crane


More information about the Edinburgh-pm mailing list