Home > Back-end >  Perl: How is to be interpreted a negation of an array and scalar?
Perl: How is to be interpreted a negation of an array and scalar?

Time:12-13

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?)

CodePudding user response:

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 = '';
  • Related