Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

Re^2: What's going on in array element assignment?

by zapdos (Sexton)
on Aug 11, 2020 at 02:53 UTC ( [id://11120588]=note: print w/replies, xml ) Need Help??

in reply to Re: What's going on in array element assignment?
in thread What's going on in array element assignment?

$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?

Replies are listed 'Best First'.
Re^3: What's going on in array element assignment?
by perlfan (Vicar) on Aug 11, 2020 at 03:20 UTC
    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.

      This is documented in perldata#Scalar-values:

      The length of an array is a scalar value. You may find the length of array @days by evaluating $#days, as in csh. However, this isn't the length of the array; it's the subscript of the last element, which is a different value since there is ordinarily a 0th element. Assigning to $#days actually changes the length of the array. Shortening an array this way destroys intervening values. Lengthening an array that was previously shortened does not recover values that were in those elements.

      You can also gain some minuscule measure of efficiency by pre-extending an array that is going to get big. You can also extend an array by assigning to an element that is off the end of the array. You can truncate an array down to nothing by assigning the null list () to it. The following are equivalent:
      @whatever = (); $#whatever = -1;

      (BTW, in my experience the speed-up to be gained by pre-allocating array memory is sometimes far from “miniscule.”)

      Hope that helps,

      Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

        Please, why
        $foo[0] = 'bedrock'; $foo[1] = 'slate'; $foo[2] = 'lava'; $foo[3] = 'schist'; @foo = ();
        makes print $#foo; result in "-1"? I don't get it. And why
        @whatever = (); $#whatever = -1;
        are equivalent?
      Domo arigato. ^__^

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11120588]
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2024-04-12 23:51 GMT
Find Nodes?
    Voting Booth?

    No recent polls found