2

What happens if I do a negation of an array or a scalar? Using the script below I got these results:

$x = 0
-------------
$x:   0
!$x:  1

$x = 1
-------------
$x:   1
!$x:  

@x = ()
-------------
@x:   
!@x:  1

@x = qw ( a b )
-------------
@x:   ab
!@x: 

I suppose that if I do a negation of a non empty array or scalar I will get '' which means in boolean context false. Is this correct?

Is there a way to make it "visible"?

What I wonder why $x=1; gives '' for !$xand not 0 since $x=0 gives 1 for !$x.

Also here I suppose that every kind of a TRUE object gives '' if negated and every kind of FALSE object gives 1 if negated.

Writing all this I got aware that Perl is very consistent. Nevertheless that the "standard" FALSE is '' (not visible) makes me uncomfortable.


Code:

my $x = 0;
print "\$x = 0\n-------------\n";
print "\$x:   ",$x,"\n";   # 0
print "!\$x:  ",!$x,"\n\n";  # 1
print "\n";

$x = 1;
print "\$x = 1\n-------------\n";
print "\$x:   ",$x,"\n";   # 1
print "!\$x:  ",!$x,"\n\n";  #    (empty?)


my @x = ();
print "\@x = ()\n-------------\n";
print "\@x:   ",@x,"\n";   # a b
print "!\@x:  ",!@x,"\n\n";  # 

@x = qw ( a b );
print "\@x = qw ( a b )\n-------------\n";
print "\@x:   ",@x,"\n";   # 1
print "!\@x:  ",!@x,"\n";  #    (empty?)
giordano
  • 2,954
  • 7
  • 35
  • 57

1 Answers1

4

The ! (not) operator puts its argument in scalar context. An array in scalar context returns its size -- how many elements it contains. So in your case, when you do

!@x

You are essentially doing:

!2

Which is the empty string, as you mentioned, and not 0.

It is not invisible, but the method you are using to display it does not show it. You could for example print it with the Data::Dumper module:

use Data::Dumper;

print Dumper !@a;

Will print

$VAR1 = '';
TLP
  • 66,756
  • 10
  • 92
  • 149
  • 1
    Re "*Which is the empty string, as you mentioned, and not `0`.*", Incorrect. It is a scalar that contains both the empty string and `0`. Actually, it contains two `0`: as an IV and as an NV. Try `perl -we'my $x = ""; $x + 0;'` and `perl -we'my $x = (!1); $x + 0;'` – ikegami Dec 10 '21 at 00:55
  • @ikegami I suppose IV and NV means integer value and double value. If I run both codes I get `Argument "" isn't numeric in addition (+) at -e line 1.` and `0` as result for the first code and `0` without warning for the second code. That means that `''` is a string (which cause the warning) but in the context it is treated as `0` that's why the result is `0`. Why `print !1` does not output `0`? How is it possible that a scalar can contain two values `''` and `0`? – giordano Dec 10 '21 at 08:55
  • 1
    @giordano, `print` needs a string, so it'll use the string in the scalar. `+ 0` needs a number, so it'll use the number in the scalar. – ikegami Dec 10 '21 at 15:49