Can someone explain me perl program behavior

$a="";
$b="n";
$c = !$a;
$d = !$b;
print $c , "\n" , $d;
if($d == 0){
    print "zero";
}

I wrote this perl program, I expected the result to be as follows.

1  
0Zero

but he prints

1  
zero

can someone explain to me why this is so?

+4
source share
4 answers

Variables in Perl are treated as numbers or strings, depending on the context. If you did not treat something as a number when assigning it, Perl will treat it as a string when printing it. A.

Because of this, false values ​​are slightly different in Perl than in languages ​​with stronger typing (highlighted by me):

0, '0' ", () undef . . ! . " ", , 0. Perl, true false, .

, , ! , . , , .

, - , . , Perl :

$d=!$b+0;
print $d;

sprintf printf :

printf '%d', $d;

int:

print int $d;

(: , , , , . . , - , Perl.)

+5

!$b '', print(), "$bool" - .

$a="";
$b="n";
$c = !$a;
$d = !$b;
print $c , "\n" , $d;
if($d == 0){
    print "zero";
}

use Data::Dumper;
print Dumper {
  '$a' => $a,
  '$b' => $b,
  '$c' => $c,
  '$d' => $d,
  '$d == 0' => $d == 0,
};

$VAR1 = {
      '$d == 0' => 1,  # boolean true
      '$b' => 'n',
      '$d' => '',      # boolean false
      '$c' => 1,
      '$a' => ''
    };
+2

perlsyn

0, '0' ", () undef . . ! . " ", , 0. Perl, true false, .

, . $a , !$a, $c, , 1. $b - , !$b, $d, . (print $c , "\n" , $d;) , . if ($d == 0) , 0, zero .

+2

Perl operators, such as !those that return booleans, return a special value for false: it is used when used in a string context and 0 when used in a numeric context.

Therefore, when you print it, it is ", not" 0 ". But if you try to use it as a number, it does not give a warning how it does" ". For comparison:

perl -wle'$false = !1; print "string: ", $false, " number: ", 0+$false'
string:  number: 0

and

perl -wle'$empty = ""; print "string: ", $empty, " number: ", 0+$empty'
Argument "" isn't numeric in addition (+) at -e line 1.
string:  number: 0
+1
source

Source: https://habr.com/ru/post/1533848/


All Articles