September 2014 Archives

I hate unpacking sub calls with shift

Perl community has moved away from using special predefined Perl variables such as $(, $), $:, $!, $^H, $/ or many others without explicitly commenting their purpose. But why are we still using shift for sub params? i.e.:

sub foo {
    my $bar = shift;

Why is it still fine within the community to skip the @_ ? If we promote shift, then lets use pop as well? Why not? it looks nice:

sub foo {
    return pop, shift;

Though I am sure someone already uses it.. how about those that use shift at line 100 inside the sub ? I hate that.. It makes really hard to follow code, for instance is it sixth or seventh unpacked argument?.. I think it’s bad practise.

I like when code is consistent and self-documenting. I love when the very first line inside the sub lists expected parameters! Just look how beautiful and tidy it looks:

sub foo {
    my ( $foo, $bar, $baz ) = @_;

You might think that it is convenient to use shift in cases like:

sub init {
    my %args = @_;
sub foo {
    my $bar = shift // ‘default’;

sub foo { shift->call() }

sub extends {
    my $meta = shift;
    if ( @_ ) {
        print “foo bar baz”;
    return @_;

sub foo {
    new $_[0], shift;
sub before {
    Foo::Bar::baz(shift, ‘before’, \@_);

But it’s horrible for newcomers! You are hurting them! What did they do to you?

  • See EXAMPLE1 and imagine you didn't understand ‘shift’. Next you google ‘Perl shift’ and probably find irrelevant information. If you add @_ i.e. 'shift( @_ )', you might have saved someone an hour.
  • how about EXAMPLE2 ? No semicolon.. no return.. and you can find this in many, many modules out there.
  • How about EXAMPLE3 ? Removing first item from @_ and then actually reusing @_ twice.
  • EXAMPLE4… aghhhh.. mixing two together..

Yet, shift might look tidier in compare to $_[0] when you are after performance and don’t want to assign named variables. But in 99% it doesn’t matter and if you need performance - document the need.

Lets start preparing for new wonderful Peter Martini’s sub signatures and tidy up.

About vytas

user-pic I am proud Perl developer since 2014. twitter: