Re: Undefined vs empty string
by BrowserUk (Patriarch) on Jun 05, 2013 at 02:30 UTC
|
Depends somewhat on what you are going to do in the body og the if, but defined and length will generally ensure that a variable is defined and contains something; so negate that:
say "'$_'", ' ', !(defined and length) ? 'go' : 'nogo' for undef, '',
+0, 'fred';;
Use of uninitialized value $_ in concatenation (.) or string at (eval
+16) line 1, <STDIN> line 8.
'' go
'' go
'0' nogo
'fred' nogo
With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
| [reply] [Watch: Dir/Any] [d/l] [select] |
|
So if my intention is to ensure that a variable is defined and contains something, should I change my code to how you have recommended or what I have is OK?
| [reply] [Watch: Dir/Any] |
|
| [reply] [Watch: Dir/Any] |
|
|
|
Re: Undefined vs empty string
by Athanasius (Archbishop) on Jun 05, 2013 at 02:29 UTC
|
undef and "" are indeed different in Perl, but both are boolean false, so the test can be simplified to:
if (!$string) {
}
See perlsyn#Truth-and-Falsehood.
Update: Except that "0" is also false, so if that’s a possibility, prefer BrowserUk’s solution, below.
Hope that helps,
| [reply] [Watch: Dir/Any] [d/l] [select] |
Re: Undefined vs empty string
by Cristoforo (Curate) on Jun 05, 2013 at 02:34 UTC
|
I think you could just write if (!$string) if you were sure $string couldn't be 0 or '0'. (a zero or zero in quotes)
Not sure if that answers your question.
Update: Just saw that Athanasius and BrowserUk posted similar answers. | [reply] [Watch: Dir/Any] [d/l] [select] |
Re: Undefined vs empty string (not length)
by Anonymous Monk on Jun 05, 2013 at 03:08 UTC
|
if( not length $var ){ ...
if( @array ) { ...
if( %hash ) { ...
See also [id://980771(on truthiness)]
| [reply] [Watch: Dir/Any] |
|
if( not length $var ){ ...
Use of uninitialized value $_ in length
With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
| [reply] [Watch: Dir/Any] [d/l] |
|
perl -Wle " print $] if not length $_ "
5.012002
| [reply] [Watch: Dir/Any] [d/l] |
|
|
|
|
|
|
Re: Undefined vs empty string
by Anonymous Monk on Jun 05, 2013 at 03:36 UTC
|
| [reply] [Watch: Dir/Any] |