develooper Front page | perl.perl5.porters | Postings from August 2003

'exists' return value in list context

Thread Next
Mark Jason Dominus
August 30, 2003 16:23
'exists' return value in list context
Message ID:

It's common to do this:

        if (exists $hash{$key}) {
          do something with $hash{$key};

This requires that the key be looked up twice.

At present, exists() does not have a useful return value in list
context.  In list context, exists() always returns true.  When the key
exists, it returns (1).  When the key does not exist, it returns (""):

      %  perl -le '@z = exists $no{such}; if (@z) { print "true" }'

This behavior contradicts the documentation, which simply asserts that
exists() returns true or false depending on the existence of the key,
and doesn't mention that exists() only does this in scalar context.

I suggest that exists() be altered so that it returns a useful value
in list context.  When $hash{$key} exists, it should return
($hash{$key}), which is true.  When $hash{$key} does not exist, it
should return (), which is false.

With this change, one could write

        if (my ($value) = exists $hash{$key}) {
          do something with $value
        } else {
          it did not exist

This works properly in all possible situations.  

It's hard for me to imagine that any old code would be broken by this
change in the behavior of 'exists' in list context, because (a) the
current behavior is useless, and (b) the current behavior contradicts
the documentation.

If there are no serious problems with this proposal, I'll do a trial
implementation and see how it goes.

Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About