in reply to exists and defined functions

Firstly, to correct the record, the exists function can be used on arrays to test the presence, defined or otherwise, of an array element.

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]

As such, your solution here will be to employ a newer version of Perl, rewrite your code to use the defined function as suggested by the other posts in this thread, or check your index against the value of $#exp (the index of the highest array element).

 

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

Replies are listed 'Best First'.
(tye)Re: exists and defined functions
by tye (Sage) on Nov 20, 2002 at 22:09 UTC

    Note that the change to make exists work on array elements was widely disliked and that I consider it, quite simply, a mistake and nothing more. Unfortunately, this mistake was made by Larry and he makes the rules. This is one of his rare bad decisions (nobody's perfect).

    Please don't use exists on array elements as the most likely result will be confusion and bugs. exists makes sense on hash elements because it distinguishes the case of the key being present with a value of undef from the case of the key not being present. For arrays, the distinction is much more subtle and is something that should never be worried about (I'd go into more details on it but I follow my own advice and don't worry about it).

            - tye