develooper Front page | perl.perl5.porters | Postings from April 2007

Re: [perl #42363] Extra elements created in multi-dimensional arrays

Thread Previous
From:
Dominic Dunlop
Date:
April 9, 2007 09:39
Subject:
Re: [perl #42363] Extra elements created in multi-dimensional arrays
Message ID:
C393B4F4-101E-45FF-9594-D54A7FD4F9B1@mac.com
On 2007–04–09, at 07:22, andyt@andy-t.org (via RT) wrote:
> While trying to write a program that makes use of a two-dimensional
> array (list of lists, to be exact), and trying to debug it, I ran into
> a possible bug.  I was trying to access a non-existing element,  
> outside
> of array boundaries, and this element, as well as all intermediate
> elements, were created for me.

It's not a bug; Perl's supposed to work this way: if you say you want  
to access a particular array element, Perl does its best to arrange  
things so that you can, even if that element does not exist. It's  
documented in passing in a number of places, under the name of  
"autovivification" (which you would never have guessed in a month of  
Sundays). See, for example, the perldata man page and, if you can  
easily look at Perl 5.8.8 or the third edition of "Programming Perl",  
perlglossary. (You filed your report using 5.8.7.)

Autovivification's generally useful as an aspect of Perl's "do what I  
mean" philosophy, but if you don't want Perl to work this way -- as  
you might not if used to Java, for example -- you'll have to write  
array-bound checks yourself: compare the proposed index against  
$#whatever -- the index of currently last element of the array --  
before using it.

For example,

$ perl -lwe '@a = ([1, 2], [3, 4, 5]); print $#a; for (0, 3) {exists  
$a[$_][0]}; print $#a'
1
3
$ perl -lwe '@a = ([1, 2], [3, 4, 5]); print $#a; for (0, 3) {exists  
$a[$_][0] unless $_ > $#a}; print $#a'
1
1

In the first case, the outer array got extended as the result of a  
test of whether an inner array element existed; in the second, the  
bounds check prevents this from happening.
-- 
Dominic Dunlop



Thread Previous


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About