Today I have encountered a problem that required me to determine the maximum index of an array in perl. I used to do it this way:
my @array = (1, 2, 3); print $array[@array - 1];
But today I have stumbled upon this code:
my @array = (1, 2, 3); print $array[$#array];
I couldn't find anything on that matter in the docs. What exactly is that $#
construct? Is that an operator? And how does it work, is it faster than the first piece of code? Does it always return the maximum array index? Is it deprecated or not?
I know that's a lot of questions, but they all can be summed up by one, and that's what I really want to know: How does it work?
This is documented in perldoc perldata, section "Scalar Values". In short, $#array
is the last index of @array
. As for how it works — it's sort of like an operator, but only as much as $
and @
are operators. Think of it as special syntax. The last index of an array just happens to "have a name". It's a variable that you can read from and assign to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With