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

Hi,
I tried the following piece of code which is not working.

$v=1; $f=!($v); print "**$f**\n";

The Output is ****. However, if i do

$v=0; $f=!($v); print "**$f**\n";

Output is **1**.

It looks like !(1) does not return zero whereas !(0) indeed returns 1. What can be the reason behind this and what should i do to get 0 from 1 by logical not.

thanks
nghosh

Edited by Ovid. 2005-07-27.

Replies are listed 'Best First'.
Re: Logical expression evaluation
by ikegami (Patriarch) on Jul 27, 2005 at 15:47 UTC
    You can format the result of ! easily using the conditional operator:
    $f = !$v ? 1 : 0;
    or just
    $f = $v ? 0 : 1;

      Or, you can instruct Perl in more detail about how you'd like a boolean value to be displayed:

      $v = 0; $f = !($v); printf '**%1d**',$f;

      Read the documentation on printf and sprintf for more.

      <-radiant.matrix->
      Larry Wall is Yoda: there is no try{} (ok, except in Perl6; way to ruin a joke, Larry! ;P)
      The Code that can be seen is not the true Code
      "In any sufficiently large group of people, most are idiots" - Kaa's Law
Re: Logical expression evaluation
by davorg (Chancellor) on Jul 27, 2005 at 15:46 UTC

    Please use <code> tags to make your code readable.

    !1 returns an empty string (which evaluates as false in a Boolean expression).

    --
    <http://www.dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: Logical expression evaluation
by Enlil (Parson) on Jul 27, 2005 at 15:51 UTC
    one way is:
    my $v=1; my $f=int( !($v) ); print "**$f**\n";

    -enlil

Re: Logical expression evaluation
by polettix (Vicar) on Jul 27, 2005 at 17:33 UTC
    Take into account that also the string '0' is considered as a false value in Perl, even if it's a non empty string. Regarding this, you'll probably find The best "true zero" is... poll useful for some popular workarounds.

    Flavio
    perl -ple'$_=reverse' <<<ti.xittelop@oivalf

    Don't fool yourself.
Re: Logical expression evaluation
by jolande (Initiate) on Jul 28, 2005 at 02:43 UTC
    You could always convert !$v into an integer before you print it. The easy way to do this is:
    v=1; $f=0+!($v); print "**$f**\n";
Re: Logical expression evaluation
by halley (Prior) on Jul 27, 2005 at 16:17 UTC
    In Perl, the logical values are typically 1 for truth, and undef for falsehood. When treated as a number, undef == 0, when treated as a string, undef eq '', all of which are treated as a false in boolean condition checks.

    --
    [ e d @ h a l l e y . c c ]

      As mentioned earlier in this thread, Perl uses "" for false. It does not use undef.
      $i = undef; print(defined($i) ? "[$i]" : 'undef', "\n"); $i = !1; print(defined($i) ? "[$i]" : 'undef', "\n"); __END__ output ------ undef []