Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does $#array mean in Perl?

Tags:

perl

I'm looking at the following code snippet:

my @ret = <someMethod>
return (undef) if( $DB_ERROR );
return (undef) unless ($#ret >= 0);

Does $# just give you a count of elements in a array?

like image 251
jcee14 Avatar asked Oct 27 '08 21:10

jcee14


Video Answer


2 Answers

$#arrayname gives you the index of the last element, so if array @ret has 2 elements then $#ret is 1.

And, as noted by Barry Brown, an empty array gives -1.

To get the length you can use the array in scalar context:

print scalar @ret;
like image 116
Ed Guiness Avatar answered Oct 07 '22 21:10

Ed Guiness


edg is correct, but the original code is unnecessarily obtuse. In most cases, $#foo is a red flag that the code could be written more simply using scalar @foo.

return (undef) unless ($#ret >= 0);

unless foo >= bar is difficult to puzzle out. First, turn it into a positive statement.

return (undef) if ($#ret < 0);

When is $#ret < 0? When it's -1. A $#ret of -1 is an array of length 0. So the above can be written much more simply as...

return (undef) if scalar @ret <= 0;

But you can't have a negative length array, so...

return (undef) if scalar @ret == 0;

And == is in scalar context, so that "scalar" is redundant...

return (undef) if @ret == 0;

But that's just a wordy way of saying "if @ret is false".

return (undef) if !@ret;

Which I think for simple statement modifiers is better expressed with unless.

return (undef) unless @ret;

Isn't that easier to follow?

As a final side-note, return undef is discouraged because it does the wrong thing in list context. You get back a list containing one undef element, which is true. Instead, just use a blank return which returns undef in scalar context and an empty list in list context.

return unless @ret;
like image 22
Schwern Avatar answered Oct 07 '22 22:10

Schwern