Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

What's going on in array element assignment?

by zapdos (Sexton)
on Aug 10, 2020 at 22:09 UTC ( #11120582=perlquestion: print w/replies, xml ) Need Help??

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 (Bishop) on Aug 10, 2020 at 22: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 10, 2020 at 22: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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://11120582]
Approved by Corion
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (3)
As of 2021-06-23 03:42 GMT
Find Nodes?
    Voting Booth?
    What does the "s" stand for in "perls"? (Whence perls)

    Results (112 votes). Check out past polls.