Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Distinguish x=undef vs x='' 1

Status
Not open for further replies.

whn

Programmer
Oct 14, 2007
265
US
Sample codes:
Code:
use Data::Dumper;

my %h; 
$h{a} = undef;
$h{b} = ''; 
$h{c} = 'z';
print Dumper(\%h); # [b]Dumper can distinguish the difference between $h{a} and $h{b}[/b]
foreach my $k (keys(%h)) {
    [b]# The following block cannot distinguish the difference between $h{a} and $h{b}[/b] 
    if(!$h{$k}) {
        print "Undefined hash value: Key - $k\n";
    }   
    else {
        print "Key: $k, Val: $h{$k}\n";
    }   
}

Sample run:
Code:
% ./tt.pl 
$VAR1 = {
          'c' => 'z',
          'a' => undef,
          'b' => ''
        };
Key: c, Val: z
Undefined hahs value: Key - a
Undefined hahs value: Key - b

Could someone show me how to distinguish them? Thanks.
 
Thank you, @prex1.

But I thought define() is obsolete?
 
'defined' not 'define()' is a perlfunc keyword operator not a method / sub, so no parentheses.

Direct quote from perl docs.

Use of defined on aggregates (hashes and arrays) is deprecated.


It all depends on what you are trying to test.

Code:
my @arr;
print defined @arr;

or 

my %hash;
print defined %hash;
is deprecated.

if you want to know if a key exists in a hash use exists

Code:
print exists $hash{key};

if you want to know whether a key has been assigned a value, use defined

Code:
print defined $hash{key};

defined is really for testing scalar values or if a subroutine is defined.


"In complete darkness we are all the same, it is only our knowledge and wisdom that separates us, don't let your eyes deceive you."

"If a shortcut was meant to be easy, it wouldn't be a shortcut, it would be the way!"
Free Electronic Dance Music
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top