Monday, 10 May 2010

@ 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)

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.

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

Page Summary

Style Credit

Expand Cut Tags

No cut tags
Page generated Monday, 7 July 2025 01:19
Powered by Dreamwidth Studios