in reply to Set Operators

if ( exists $set{$a} ) { ... }

but it only works for hashes.
If you really want "sets" there is a whole Set directory in CPAN.
(I'm guilty of Set::Infinite but there are many other modules)

Replies are listed 'Best First'.
Re: Re: Set Operators
by rob_au (Abbot) on Oct 25, 2002 at 10:10 UTC
    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"'

      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.