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.
no subject
Date: Monday, 10 May 2010 11:01 (UTC)scalar @foo
Date: Monday, 10 May 2010 12:13 (UTC)no subject
Date: Monday, 10 May 2010 15:43 (UTC)no subject
Date: Monday, 10 May 2010 18:10 (UTC)no subject
Date: Tuesday, 11 May 2010 00:58 (UTC)no subject
Date: Tuesday, 11 May 2010 05:42 (UTC)