@ vs. $#

Monday, 10 May 2010 11:19
pne: A picture of a plush toy, halfway between a duck and a platypus, with a green body and a yellow bill and feet. (Default)
[personal profile] pne

I was reading a tutorial on Perl autovivification and came across this bit of code, testing whether a number was a valid array index:

return unless 0 <= $key && $key < @{$ref} ;

And I thought “meh”, because the author used @{$ref} in a comparison for a valid index.

I would have used && $key <= $#{$ref} (well, actually probably $#$ref) instead.

Because, for me, @foo (in scalar context) is the number of entries in @foo, so you’d use it for things like seeing whether you have enough arguments to a subroutine, or whether an array is empty, or that sort of thing: where you’re interested in the number of entries. $#foo, on the other hand, is the last valid index in @foo, so you’d use it when you’re interested in valid indices (indexes?) such as the comparison above or the classic for ($i = 0; $i <= $#foo; $i++) C-style for loop over the indices of an array.

Sure, the two are related to one another (@foo is one more than $#foo, unless you’ve messed with $[, which you probably shouldn’t), but for me, the two are semantically different, and using either expression in something semantically related to the other feels wrong to me.

Of course, YMMV; Perl is (at least supposedly) all about TMTOWTDI and accepting of others’ programming styles. So I’ll just say that that’s how I think of them.

(will be screened)
(will be screened if not validated)
If you don't have an account you can create one now.
HTML doesn't work in the subject.
More info about formatting

If you are unable to use this captcha for any reason, please contact us by email at support@dreamwidth.org

Profile

pne: A picture of a plush toy, halfway between a duck and a platypus, with a green body and a yellow bill and feet. (Default)
Philip Newton

June 2015

S M T W T F S
 12 3456
78910111213
14151617181920
2122232425 2627
282930    

Most Popular Tags

Style Credit

Expand Cut Tags

No cut tags
Page generated Wednesday, 16 July 2025 09:28
Powered by Dreamwidth Studios