Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do dollar and number sign together work in perl?

Tags:

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?

like image 848
Igor Zinov'yev Avatar asked Dec 23 '11 17:12

Igor Zinov'yev


1 Answers

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.

like image 164
hobbs Avatar answered Sep 29 '22 09:09

hobbs