Gossamer Forum
Home : General : Perl Programming :

defined

Quote Reply
defined
If I'm doing an if ($something) { do something } statement. Is it safer to change that to if (defined $something) or doesn't it matter?

- wil
Quote Reply
Re: [japh] defined In reply to
>>How should I know?! Do some searching. There's plenty of refernece on google.com<<

...and here's one:

http://www.rocketaware.com/...perlfunc/defined.htm
Quote Reply
Re: [RedRum] defined In reply to
Yes, that is one that doesn't answer my question.

Thank you, anyway.

- wil
Quote Reply
Re: [japh] defined In reply to
Sure it does. That is the official perldoc content for defined()

Whether it is safe or not depends on what you are trying to achieve but the url above seems to explain how to use defined fairly clearly and in which circumstances IMO. It's a question of does it do what you want/expect it to do, not whether it is safer.

Last edited by:

RedRum: Jan 16, 2002, 3:57 AM
Quote Reply
Re: [RedRum] defined In reply to
Well, both do what I want. i.e.:

Code:
if (defined $scalar) { ...

and

if ($scalar) { ...

But which one to use for this type is unclear. $scalar is passed to the script via CGI, so maybe not using define would be best?

- wil
Quote Reply
Re: [japh] defined In reply to
What is contained in $scalar?....if it contains a false value eg 0 or '' then it could make a difference, otherwise either of the options you pasted above are fine.

Last edited by:

RedRum: Jan 16, 2002, 4:59 AM
Quote Reply
Re: [RedRum] defined In reply to
It contains a string, it actually contains a filename. If it doesn't contain a filename, then it doesn't contain anything, ie it's not passed to the script at all.

- wil
Quote Reply
Re: [japh] defined In reply to
It makes a difference in the following case:
Code:
my $q = new CGI;

if (defined $q->param('query')) {
...
}
or
Code:
my $q = new CGI;

if ($q->param('query')) {
...
}

If you enter script.cgi?query=words, both cases will be true.

If you enter script.cgi?query=, the first case will be true, whereas the second will not be true.

If you enter script.cgi, none of them will be true.

Does that help?

Ivan
-----
Iyengar Yoga Resources / GT Plugins

Last edited by:

yogi: Jan 16, 2002, 5:18 AM
Quote Reply
Re: [yogi] defined In reply to
Great. Thank you for that. That does clear my head. It seems to simple and logical when you put it like that <g>.

The second case is the one I want then.

Thanks.

- wil