perlpal has asked for the wisdom of the Perl Monks concerning the following question:

Hi PerlMonks, Seeking you assistance for the following :

I am trying to print a scalar(string or numeric) only when it is not equal to an empty string "" and 0 . The code below works correctly for $key,$key2 and $key3 but not $key1;

#!/usr/bin/perl $key = 1; $key1 = "test"; $key2 = ""; $key3 = 0; if (($key ne "") && ($key != 0)){ print "\n$key\n"; } OUTPUT : Correct For $key : 1 Incorrect For $key1 : Correct For $key2 : Incorrect For $key3 :

Replies are listed 'Best First'.
Re: If condition logic yielding partially correct output
by JavaFan (Canon) on Aug 13, 2009 at 10:54 UTC
    The problem is that you're comparing "test" numerically. "test" as a number is 0. 0 != 0 is false.

    Assuming you don't want to print the key when it's undefined either, you could do:

    print "\n$key\n" if $key;
Re: If condition logic yielding partially correct output
by Old_Gray_Bear (Bishop) on Aug 13, 2009 at 11:02 UTC
    Take a look at What is true and false in Perl. The string 'test' (being not equal to an empty string) passes your first clause; and since the string 'test' is not equal to the string '0', in numeric context, it passes the second clause. Since 1 && 1 evaluate to 1, 'test' satisfies your if condition.

    Update -- clarified that we are talking about strings in the second clause

    ----
    I Go Back to Sleep, Now.

    OGB

      Erm... "test" is equal to 0 in numeric context, so if (($key ne "") && ($key != 0)) evaluates as false for "test" ("test" ne "" is true, "test" != 0 is false; true && false = false), which is why the print after the if doesn't execute.
Re: If condition logic yielding partially correct output
by Utilitarian (Vicar) on Aug 13, 2009 at 10:54 UTC
    Only use != for numeric scalars. So
    if (($key ne "") && ($key !~ /^[0.]+$/ ))){
    If you don't know before hand which it is, treat it as a string, downside of weak typing for those asking about relative merits of Perl on whatever course you're doing ;)

    Update: Actually scratch all that JavaFan's answer is a much better solution

Re: If condition logic yielding partially correct output
by Anonymous Monk on Aug 13, 2009 at 11:07 UTC
Re: If condition logic yielding partially correct output
by bobf (Monsignor) on Aug 14, 2009 at 03:00 UTC