Brutha has asked for the wisdom of the Perl Monks concerning the following question:

Hello fellow monks,

testing is a great thing, especially if you find something like the following

my @y; print "Array is empty: ", (0 == scalar @y ? "yes" : "no"), "\n"; print "first element: ", ( $y[0] ? "defined" : "undefined"), "\n"; print "Array is empty: ", (0 == scalar @y ? "yes" : "no"), "\n"; print "Type of first element: ", ref \$y[0], "\n"; print "Array is empty: ", (0 == scalar @y ? "yes" : "no"), "\n";

You find that reading 0th element from an empty array gives undefined and leaves the array untouched. But using ref on that non-existing element creates it and returns scalar.

It took me an hour to find why my array was not empty. Could anybody explain this a bit? Somwhow, I feel like a beginner again.

And it came to pass that in time the Great God Om spake unto Brutha, the Chosen One: "Psst!"
(Terry Pratchett, Small Gods)

Replies are listed 'Best First'.
Re: ref defines array element?
by broquaint (Abbot) on Oct 07, 2003 at 12:39 UTC
    This is yet another case in the ongoing trial of perl's auto-vivification. What's happening there is that by creating a reference to the first element of @y you are forcing it into existence, however it will still be undefined as you have yet to assign anything to it e.g
    use Data::Dumper; $Data::Dumper::Terse = 1; $Data::Dumper::Indent = 1; my @y; print 'pre auto-vivify: ', Dumper(\@y); print 'reference to $y[0]: ', Dumper(\$y[0]); print 'post auto-vivify: ', Dumper(\@y); __output__ pre auto-vivify: [] reference to $y[0]: \undef post auto-vivify: [ undef ]
    HTH

    _________
    broquaint

Re: ref defines array element?
by Abigail-II (Bishop) on Oct 07, 2003 at 13:00 UTC
    Easy. You create a reference. It's impossible in Perl to have a reference pointing to nothing - it always has to point to something, even if that something is undefined. You ask Perl to create a reference to $y [0]. $y [0] doesn't exist yet, so Perl conveniently creates it for you, just as it would do if you assign to it.

    Now, after you are done with the 'ref', the reference disappears due to garbage collection, but $y [0] doesn't, as it's now in the array and hence still has a ref count of 1.

    Abigail