Philip Newton (pne) wrote,
Philip Newton

  • Mood:

@ vs. $#

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.

Tags: perl, programming
  • Post a new comment


    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded