Does Perl auto-vivify variables used as references in subroutine calls?

Posted by FM on Stack Overflow See other posts from Stack Overflow or by FM
Published on 2010-04-18T14:11:00Z Indexed on 2010/04/18 14:13 UTC
Read the original article Hit count: 314

Filed under:
|
|

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:

  1. Am I understanding this behavior correctly?

  2. What is the explanation or reasoning behind why Perl does this?

  3. Is this behavior explained anywhere in the docs?

© Stack Overflow or respective owner

Related posts about perl

Related posts about subroutine