Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undef value assigned to variable.

Tags:

undefined

perl

The return value of 5 > 6 is undef. However when I assign the value of 5 > 6 to a variable that variable is defined. How do I pass the value of a statement using a comparison operator that resolves to undef on failure?

#!/usr/bin/perl
use strict ;
use warnings;
print'Five is more than six ? ',      5 >  6, "\n";
print 'Five is less than six ? ' , 5 < 6 , "\n";
my $wiz = 5 > 6 ;

if (defined($wiz)) {
    print '$wiz is defined' ;
    } else {
    print '$wiz is undefined' ;
}


$ ./lessthan
Five is more than six ?
Five is less than six ? 1
$wiz is defined
like image 253
capser Avatar asked Oct 18 '25 12:10

capser


2 Answers

How do I pass the value of a statement using a comparison operator that resolves to undef on failure?

Generally speaking, Perl doesn't promise to return any specific true or false value from its operators, and < is no exception. If you want specific values, you will need something like

$boolean ? $value_for_true : $value_for_false

so

my $wiz = 5 > 6 ? 1 : undef;

If you only care about the value you get for false, you could also use the following:

my $wiz = 5 > 6 || undef;

The two options turn out to be equivalent, but this isn't guaranteed.


The return value of 5 > 6 is undef. However when I assign the value of 5 > 6 to a variable

That's not true. The variable is assigned a defined value because 5 > 6 evaluated to a defined value. While Perl doesn't specify what false value it returns from it's operators, it usually returns the scalar sv_no, which is a dualvar that appears to be an empty string when treated as a string, and zero when treated as a number.

$ perl -wE'say "> ", "".( undef )'
Use of uninitialized value in concatenation (.) or string at -e line 1.
>

$ perl -wE'say "> ", "".( "" )'
>

$ perl -wE'say "> ", "".( 0 )'
> 0

$ perl -wE'say "> ", "".( 5>6 )'
>                                     # Behaves as ""

$ perl -wE'say "> ", 0+( undef )'
Use of uninitialized value in addition (+) at -e line 1.
> 0

$ perl -wE'say "> ", 0+( "" )'
Argument "" isn't numeric in addition (+) at -e line 1.
> 0

$ perl -wE'say "> ", 0+( 0 )'
> 0

$ perl -wE'say "> ", 0+( 5>6 )'
> 0                                   # Behaves as 0
like image 120
ikegami Avatar answered Oct 21 '25 01:10

ikegami


5 > 6 is not undefined, but it is a false value. In this case, a dualvar that acts like an empty string when used as a string, or 0 when used as a number.

Because the value is false, you can just do

if ( $wiz ) { ... }

If you really want $wiz to be undefined, you could do something like this.

my $wiz = 5 > 6 || undef;

Now, if the expression 5 > 6 is true, $wiz will be 1, otherwise it will be undef.

like image 28
Joshua Avatar answered Oct 21 '25 02:10

Joshua



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!