Does Perl auto-vivify variables used as references in subroutine calls?
- by FM
I've declared 2010 to be the year of higher-order programming, so I'm learning Haskell. The introduction has a slick quick-sort demo, and I thought, "Hey, that's easy to do in Perl".
It turned to be easier than I expected. Note that I don't have to worry about whether my partitions ($less and $more) are defined. Normally you can't use an undefined value as an array reference.
use strict;
use warnings;
use List::MoreUtils qw(part);
my @data = (5,6,7,4,2,9,10,9,5,1);
my @sorted = qsort(@data);
print "@sorted\n";
sub qsort {
return unless @_;
my $pivot = shift @_;
my ($less, $more) = part { $_ < $pivot ? 0 : 1 } @_;
# Works, even though $less and $more are sometimes undefined.
return qsort(@$less), $pivot, qsort(@$more);
}
As best I can tell, Perl will auto-vivify a variable that you try to use as a reference -- but only if you are passing it to a subroutine. For example, my call to foo() works, but not the attempted print.
use Data::Dumper qw(Dumper);
sub foo { print "Running foo(@_)\n" }
my ($x);
print Dumper($x);
# Fatal: Can't use an undefined value as an ARRAY reference.
# print @$x, "\n";
# But this works.
foo(@$x);
# Auto-vivification: $x is now [].
print Dumper($x);
My questions:
Am I understanding this behavior correctly?
What is the explanation or reasoning behind why Perl does this?
Is this behavior explained anywhere in the docs?