Skip to content

Use array references with the array operators

There's a significant change in syntax showing up in Perl 5.14. The array operators push, pop, shift, and unshift previously only worked on named arrays or dereferenced references. Now, thanks to David Golden, they'll work on array references. Not only that, they'll work on references that you've stored in variables or that come as the return values from subroutine calls. This feature will show up in Perl 5.13.7, so you need to compile a development version to try this:

my $ref = [ qw(Buster Mimi Ginger Ella) ];

sub get_dogs { [ qw(Nicki Addy) ] }

push $ref, 'Addy';
print "Pets are @$ref\n";

my $dog = shift get_dogs();
print "Dog is $dog\n";

This brings some Perl 6 ideas into Perl 5: where you can use an array, you can use things that act like arrays. This blurs the difference between a named array and a reference to it so Perl has even more DWIMery.

As of today, you have to compile the latest version of blead to try out this feature:

$ blead arrays2.pl
Pets are Buster Mimi Ginger Ella Addy
Dog is Nicki

Prior to Perl 5.14, perl would catch these errors at compile-time and tell you what it found and what it expected:

% perl5.12.2 array_operators.pl
Type of arg 1 to push must be array (not private variable) at arrays.pl line 5, near "'Addy';"
Type of arg 1 to shift must be array (not subroutine entry) at arrays.pl line 8, near ");"
Execution of arrays.pl aborted due to compilation errors.

To fix this, you have to use the ungainly dereferencing syntax:

my $ref = [ qw(Buster Mimi Ginger Ella) ];

sub get_dogs { [ qw(Nicki Addy) ] }

push @$ref, 'Addy';
print "Pets are @$ref\n";

my $dog = shift @{ get_dogs() };
print "Dog is $dog\n";

It's ugly, but it works:

$ perl5.12.2 arrays2.pl
Pets are Buster Mimi Ginger Ella Addy
Dog is Nicki

If you want to get rid of the uglies, get ready to upgrade to Perl 5.14.