You should never use defined on hashes nor on arrays and you should never use exists nor delete on array elements. These all tell you stuff about whether memory has been allocated for the items, which is an internals thing that no script should ever have to care about. The correct replacements are:
You can leave off the scalar call in many cases, of course.defined %hash scalar keys %hash defined @array scalar @array exists $array[$elt] defined $array[$elt] (and/or) 0 <= $elt && $elt < @array delete $array[$elt] undef $array[$elt] (or) splice( @array, $elt, 1 )
Also, you are mistaken about return;. It doesn't return undef in a list context, it returns () (it does return undef in a scalar context). So you need to fix your function and you'll probably have to return that error condition "out of band". If your existing code happens to work in that case (I don't think it would, but I haven't tested), then that is more by accident than by design.
Update: No, the current code doesn't even work:
yields only: @ar1 is definedsub all_between { my ($min, $max ) = @_; if ( $min > $max ) { return; } my @array = (); my $i = $min + 1; while ($i < $max) { push @array, $i++; } return @array; } my @ar1 = all_between( 4, 10 ); # Gives (5,6,7,8,9) my @ar2 = all_between( 4, 5 ); # Gives () my @ar3 = all_between( 4, 3 ); # Gives undef print "\@ar1 is defined\n" if defined @ar1; print "\@ar2 is defined\n" if defined @ar2; print "\@ar3 is defined\n" if defined @ar3;
Update 2: I never before noticed that an empty hash doesn't report its number of buckets in a scalar context.
- tye (but my friends call me "Tye")In reply to (tye)Re: Replacement for defined(%)/defined(@)?
by tye
in thread Replacement for defined(%)/defined(@)?
by Masem
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |