go ahead... be a heretic PerlMonks

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

by zapdos (Sexton)
 on Aug 12, 2020 at 04:37 UTC Need Help??

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

Replies are listed 'Best First'.
Re^6: What's going on in array element assignment?
by Athanasius (Archbishop) on Aug 12, 2020 at 06:24 UTC

Hello zapdos,

To access an element in an array, you specify the index of the element you want. But in Perl (as in C), the first index is not one but zero (0). If the array is named @foo, there is a special Perl syntax to give you the largest index: \$#foo. Consider this array:

```my @foo = ('bedrock', 'slate', 'lava', 'schist');
#  index:      0         1       2        3

As you can see, the array has 4 elements.1 Because the indexes start at zero, these 4 elements have indexes 0, 1, 2, and 3, respectively. The largest index, in this case 3, can be found by accessing the special \$#foo variable.

By assigning to \$#foo you change the value of its largest index, and thereby re-size the array. For example, if you say \$#foo = 2 you make \$foo[2] the last element in the array. As a consequence \$foo[3], formerly 'schist', ceases to exist. In other words, the array is truncated. If instead you were to say \$#foo = 5, you would be adding two new elements to the array, each with an undefined value:

```@foo = ('bedrock', 'slate', 'lava', 'schist', undef, undef);
# index:    0         1       2        3        4      5

Now, the first element of the array (in this case with the value 'bedrock') has index 0, as explained above. So if you were to say \$#foo = 0, you would be saying “make 0 the largest index into array @foo” — after which the array would contain exactly one element, namely \$foo[0] with value 'bedrock'. If you wanted to truncate the array all the way down to zero elements, the largest index would have to be less than zero, so you write \$#foo = -1, which produces an empty array. So does assigning an empty list to the array: @foo = (); And that’s why the assignments @foo = () and \$#foo = -1 are equivalent.

1You can find the number of elements by putting the array variable into scalar context, e.g., my \$number_of_elements = scalar @foo;.

Hope that helps,

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

Arigato gozaimasu, Athanasius. I love you. ;-)

Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11120641]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others chilling in the Monastery: (5)
As of 2024-04-24 19:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?

No recent polls found