What does Perl return when a numeric comparison is false?
I am trying to execute this code. What puzzles me is why this comparison does not return any value when false. Is this the default behavior of these comparison operators?
my $output = (2 <= 1);
print "value=$output";
Will the comparison operator return undef
if its logical check fails?
source to share
return 1 for true and a special version of the specified empty string, ", which is considered null, but is exempt from warnings about incorrect numeric conversions, just like" 0 but true ".
The value you are returning is actually double. It has separate numeric and string values ββ(it is not actually a special version of the empty string). The numeric value is 0 and the string value is an empty string. You used a string that is empty but 0 still exists. You can view the variable entries using Devel :: Peek :
use Devel::Peek;
my $result = ( 1 == 2 );
Dump( $result );
In the SV (scalar value) value behind the scenes, you see the string value in PV and the numeric value in IV and NV (integer and numeric values):
SV = PVNV(0x7fe602802750) at 0x7fe603002e70
REFCNT = 1
FLAGS = (PADMY,IOK,NOK,POK,pIOK,pNOK,pPOK)
IV = 0
NV = 0
PV = 0x7fe6026016b0 ""\0
CUR = 0
LEN = 16
There are other types of double cards. For example, an error variable has an error $!
number and an error text (and I talk about this in Mastering Perl ). This is not something you usually have to worry about, because Perl does the right thing for context.
If you always want a numeric value, use it in a numeric context:
my $numeric = 0 + $result; # 0
You can create your own double disks with Scalar :: Util dualvar
and you can check if the scalar is double with isdual
.
use Scalar::Util qw(isdual);
my $result = ( 1 == 2 );
print isdual($result) ? "dualvar" : "Not dualvar";
If you want to check that the value you got was defined (you said it wasn't), you can check with defined . Although the empty string is defined. If you want to check that it is not an empty string, you can use length . They help when the value you have cannot be printed.
source to share
Comparisons can return a special false value, which is an empty string or 0, depending on the context in which it was evaluated. If you're looking for specific values ββfor true and false, it's much safer to use an operator like this:
my $output = ( 2 <= 1 ) ? 1 : 0;
The following code illustrates the behavior of a special false value.
use 5.014;
say ( 2 <= 1); # prints nothing
my $output = ( 2 <= 1 ) ? 1 : 0;
say $output; # prints 0
$output = ( 2 > 1 ) ? 1 : 0 ;
say int $output; # prints 1
say $output; # prints 1
$output = ( 2 <= 1 ) ;
say int $output ; # prints 0
If you are not familiar with ?: build see: http://perldoc.perl.org/perlop.html#Conditional-Operator
source to share