in reply to Re: Re: Re: optimization - exists should return a reference
in thread optimization - exists should return a reference
"If exists is to return a reference, it should always return a reference."
I don't know about that. Let's say we're looking at exists($foo{'bar'}). So, if $foo{'bar'} exists, exists returns a reference to it. Otherwise, it returns undef or an empty string, or 0 or whatever the hell. Something that's false in a boolean context. One potential problem, as you point out, is if someone tries to dereference the result without checking to see if it's true first. (I'll assume for the time being that it's out of the question to change the way references evaluate in boolean context :o)
I would say that checking for the existance of the value returned by exists is pretty natural. For instance the example put forward by BrowserUK:
use strict 'refs'; print ${exists $foo{'bar'}};
would yield Can't use an undefined value as a SCALAR reference or something of the like. This would be an example of bad coding: using a value without being sure that there is a value. It's really no different from: The same mistake is made (and the same error potentially generated) as if the following were written:
use strict 'refs'; print ${$foo{'bar'}};
This would yield the same error. Whereas one 'right' way to do the same thing would be:
One 'right' way to use the reference from the proposed exists would be:
use strict 'refs'; print ${exists $foo{'bar'} || \"" };
...perhaps substituting a reference to a default value or somesuch for the \"". What I'm saying is that this puts responsibility on the programmer to make sure she doesn't try to dereference anything undefined or whatever. If she wants to be able to do stuff like print ${exists $foo{'bar'}} she's not going to use strict. For the rest of us, we get added functionality for exists that doesn't break existing code.
Update: The crux, in my mind, of why print ${exists $foo{'bar'}} doesn't make sense just finally came to me in actual words: it's like writing print ( if ($foo{'bar'}) ), or print ( $foo > $bar ). It's a boolean test, which is not designed to stand alone. Conceptually, exists exists to choose between two options.
Update: Aristotle pointed out some ambiguity in the way I phrased some stuff. Also, I noticed that in my first paragraph I had written exists $foo instead of exists $foo{'bar'}.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^5: optimization - exists should return a reference
by Aristotle (Chancellor) on Jan 15, 2003 at 23:06 UTC | |
by LAI (Hermit) on Jan 16, 2003 at 16:11 UTC |