Domanda

my $line = "hello";
print ($line == undef);

The check should be false since $line is not undefined (I defined it in the first line). Why is this code snippet printing out '1'?

È stato utile?

Soluzione

It's doing exactly what you said.

print ($line == undef);

You're printing out a boolean value because ($line == undef) is a boolean statement.

The == is a numeric equals. Since $line is text, it has the value of 0. So does undef numerically. Thus ($line == undef) is true.

You should always put the following on the top of your program:

use strict;
use warnings;

There are other pragmas people put, but these are the two most important. They will find 90% of your errors. Try this program:

use strict;
use warnings;
my $line = "hello";
print ($line == undef)

You'll get:

Use of uninitialized value in numeric eq (==) at ./test.pl line 6.
Argument "hello" isn't numeric in numeric eq (==) at ./test.pl line 6.

Of course I have an uninitialized value! I'm using undef. And, of course hello isn't a numeric value.

I'm not entirely sure what you want. Do you want to print out hello if it's not defined? Are you trying to see the value of that boolean statement?

What about that \n on the end that print doesn't put on the end of the line? Do you want that? Because print can be prone to the forgotten \n error, I prefer to use say:

use strict;
use warnings;
use feature qw(say);   # Say is like print but includes the ending `\n`

my $line = "hello";
say (not defined $line);    # Will print null (false) because the line is defined
say ( defined $line);       # Will print "1" (true).
say ( $line ne undef);      # Will print '1' (true), but will give you a warning.
say $line if defined line;  # Will print out $line if $line is defined

Altri suggerimenti

Always put

use strict; use warnings;

or

use Modern::Perl;

you will see some errors :

Use of uninitialized value in numeric eq (==) at /tmp/sssl.pl line 3.
Argument "hello" isn't numeric in numeric eq (==) at /tmp/sssl.pl line 3.

To test if a variable is defined, use :

print "variable defined" if defined $variable;

To test a string against another string, use :

if ($string eq $another_string) { ... }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top