> This distinction between canonical existence and logical existence--or
> perhaps more properly the distinction between the existence of an
> element and of a position--is important because, while useful, the
> distinction does have implications for the value of $#array, the
> return value of scalar(), and the behavior of while and foreach
> blocks, among others, not just the output of Data::Dumper.
Until this thread, I had never considered trying to delete an array
element, having imagined it as meaningless in an array.
I've been experimenting a bit with this
(context: This is perl, v5.8.8 built for sun4-solaris)
Delete does not affect $#array or scalar(@array) except in one case:
'delete $array[$ii];' will leave array in the same state as 'pop @array'
iff $ii is equal to $#array;
Note that the opposite is NOT true -- delete $array[0] is not the same
as shift @array.
(Caveat: I have not tested how altering $[ may affect this ... Those
who change $[ are painting a giant "kick me" sign on their code and
get what they deserve :)
Some code to demonstrate...
local $\ = "\n"; # as if perl -l
my @sparse = qw / one two three four five / ;
delete $sparse[0]; # no 'one'
delete $sparse[$#sparse]; # truncate the last
push @sparse, undef;
print "Checking existance...";
print for map "\$sparse[$_] = $sparse[$_]", grep exists $sparse[$_],
0..$#sparse;
# expect a couple of unitialized value warnings
print "Checking definedness...";
print for map "\$sparse[$_] = $sparse[$_]", grep defined $sparse[$_],
0..$#sparse;
If you remove the push @sparse,undef then both loops give the same results.
If there were[1] a keys-like operator for arrays (e.g. indices @foo)
It would strike me as a mitzvah if it were to return the same list as
the grep exists clause in the example above[2]
Another data point: copying an array (e.g. my @other = @sparse; )
"loses" the existance characteristic ... that is: $other[0] and
$other[4] both exist and are undefined ( $sparse[0] did not exist ,
$sparse[4] exists but is not defined )
[1] Note the use of the subjunctive mood - indicating statement
contrary to reality. However, writing it is trivial:
sub indices { return grep exists $_[$_],0..$#_; }
[2] 'cuz THEN you could do my @compacted = @foo[indices @foo];
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/