Pergunta

Suppose it is:

...
use Config::Properties::Simple;
...
my $p = Config::Properties::Simple->new( file => $propfile );
...
$str = $p->getProperty('prop');
...

.

Does

 ...
if ( defined $str and $str ne "" ) { #1
 ...

equal to

...
if ($str) { #2
...

?

If not, is there a way to simplify the #1 marked statement?

Foi útil?

Solução

No, they're not the same if $str is "0".

You can simplify the statement by just checking the length:

if (length $str) { ...

In recent versions of Perl, length(undef) is undef without any warning generated. And using undef as a boolean doesn't generate a warning either.

(By "recent" I mean 5.12 and up. Previously, length(undef) would produce "Use of uninitialized value in length" if you have warnings turned on, which you should.)

Outras dicas

  1. No. It's different for $str=0; and $str="0"; for starters.

  2. Maybe. Depends on what values $str can have, what you are checking for and what version of Perl you want to support. Possibilities:

    • if ($str)
    • if (length($str))
    • if (defined($str))
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top