Pergunta

I am using Getopt::Std in a Perl script, and would like to pass in a zero as value. I am checking that values are set correctly using unless(). At the moment unless() is rejecting the value as being unset.

Is there a way to get unless() to accept zero as a valid value (any non-negative integer is valid).

This is probably perfeclty simple, but I've never touched Perl before a few days ago!

Rich

Foi útil?

Solução

You need to use unless defined <SOMETHING> instead of unless <SOMETHING> , because zero is false in Perl.

Outras dicas

Perl 5 has several false values: 0, "0", "", undef, ().

It is important to note that some things may look like they should be false, but aren't. For instance 0.0 is false because it is number that is equivalent to 0, but "0.0" is not (the only strings which are false are the empty string ("") and "0").

It also has the concept of definedness. A variable that has a value (other than undef) assigned to it is said to be defined and will return true when tested with the defined function.

Given that you want an argument to be a non-negative integer, it is probably better to test for that:

unless (defined $value and $value =~ /^[0-9]+$/) {
    #blah
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top