http://www.perlmonks.org?node_id=11120582

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

So I'm following the book Learning Perl, there's this code with comments in it:
$rocks[0] = 'bedrock'; $rocks[1] = 'slate'; $rocks[2]= 'lava'; $rocks[3] = 'crushed rock'; $rocks[99] = 'schist'; $#rocks = 2; # forget all rocks after 'lava' $#rocks = 99; # add 97 undef elements (the forgotten rocks are gone fo +rever)
If I do print $rocks[$#rocks]; it prints nothing. Why? When I comment out $#rocks = 99; it prints 'lava' and when I comment out $#rocks = 2; it prints 'schist'. But when I maintain the two it prints nothing as I already said. And what the comments "add 97 undef elements (the forgotten rocks are gone forever)" and "forget all rocks after 'lava'" mean?

Replies are listed 'Best First'.
Re: What's going on in array element assignment?
by AnomalousMonk (Archbishop) on Aug 11, 2020 at 02:17 UTC
    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: What's going on in array element assignment?
by perlfan (Vicar) on Aug 11, 2020 at 02:36 UTC
    This paints a better picture:
    use strict; use warnings; use Data::Dumper (); my @rocks = (); $rocks[0] = 'bedrock'; $rocks[1] = 'slate'; $rocks[2]= 'lava'; $rocks[3] = 'crushed rock'; print Data::Dumper::Dumper(\@rocks); $rocks[99] = 'schist'; print Data::Dumper::Dumper(\@rocks); $#rocks = 2; # forget all rocks after 'lava' print Data::Dumper::Dumper(\@rocks); $#rocks = 99; # add 97 undef e print Data::Dumper::Dumper(\@rocks);
    Also, if you want to do surgery on your array, look at splice.
      $rocks[0] = 'bedrock'; $rocks[1] = 'slate'; $rocks[2]= 'lava'; $rocks[3] = 'crushed rock'; $rocks[99] = 'schist'; $#rocks = 2; $#rocks = 99; print $rocks[$#rocks];
      So print $rocks[$#rocks]; is printing nothing because the last element is undef?
        Yes, $#rocks = 2; made your array unaware of subsequent elements (though the memory may still be intact, but I don't think the underlying datastructure can be reverted easily); however $#rocks = 99; probably overwrote the memory forever with undefs. I don't know what memory managment magic is invoked here, but I think on a high level that's an accurate way to think about it.