in reply to Re: Set Operators
in thread Set Operators

but it only works for hashes.

As of Perl 5.6.0, the exists function can be used on arrays to test the existence of an element within an array. For example:

my %hash = ( 'key' => 'value' ); print "exists \$hash{'key'}\n" if exists $hash{'key'}; my @array = ( 'value' ); print "exists \$array[\$index]\n" if exists $array[0];

Under Perl 5.005.03 this code results in an error:

exists operator argument is not a HASH element at test-5.00503.perl li +ne 7.

Whereas, under Perl 5.6.0 or later, the code executes without error:

exists $hash{'key'} exists $array[$index]

Cool huh? Much nicer than using a construct like ($index <= $#array) to test the existence of an array element - Especially if someone is performing magic with $[ !

 

perl -e 'print+unpack("N",pack("B32","00000000000000000000000111010111")),"\n"'

Replies are listed 'Best First'.
Re: Re: Re: Set Operators
by dbp (Pilgrim) on Oct 25, 2002 at 19:02 UTC
    Does anyone know how the exists function is implemented for arrays? Is it the equivalent of a linear search through the array, or is it more interesting? Essentially, does it have a worst case time complexity better than N? Oops. Didn't read that very carefully. Thought you could do an exists on a value, not an index.