SPUG: argument-less shift - explicit/implicit [was: Hashes and subroutines]

Michael R. Wolf MichaelRWolf at att.net
Wed Jan 7 13:31:56 PST 2009

On Jan 6, 2009, at 8:16 PM, Jack Foy wrote:

> Paul Goracke wrote:

> sub runCommand {
> 	my $command = shift;
> 	my $rArgs = shift;	# or use @_, but see note 1
> [...]
> # Note 1: I avoid using @_ directly.  This both makes the code  
> easier to
> # read by making routine arguments explicit, and avoids accidental
> # aliasing.

This seems backwards to my way of thinking (i.e. my way of reading and  
writing code for my own and other's use):
     You use @_ *implicitly*, but state that *explicit* code is easier  
to read.

<begin personal preference>
Since shift without an argument has two different implicit arguments,  
depending on whether it's inside (@_) or outside (@ARGV) of a  
subroutine, this is one case where I'm diligent about being explicit  
about the arguments.  I do that for readability.

To my eyes, I think the first chunk of code is more explicit, and  
therefore readable.

# EXPLICIT args to shift...
my $script_arg = shift @ARGV;

sub xxx {
     my $subroutine_arg = shift @_;

# IMPLICIT args to shift...
my $script_arg = shift;

sub xxx {
     my $subroutine_arg = shift;

I actually prefer the unpacking idiom as being much more explicit (for  
my definition of 'explicit'):
sub xxx {
     my ($first_arg, $second_arg, @remaining_args) = @_;

I think that explicitly stating the argument to shift prevents the  
reader from having to keep the context in their head, therefore frees  
their mind for higher level tasks.

<end personal preference>

Call it a "personal preference", or a "well-understood idiom", or a  
"group standard" if you wish, but I think using an implicit argument  
is *NOT* more explicit.

Michael R. Wolf
     All mammals learn by playing!
         MichaelRWolf at att.net

More information about the spug-list mailing list