Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re^2: restricting values to a nested datastructure

by zwon (Abbot)
on Dec 14, 2011 at 14:27 UTC ( [id://943558]=note: print w/replies, xml ) Need Help??


in reply to Re: restricting values to a nested datastructure
in thread restricting values to a nested datastructure

if (exists $a{'abd'} and exists $a{'abd'}->[0] and defined $a{'abd'}->[0])

There's no need to use exists. You know that $a{abd} is a reference if it exists, so just check if it is true. exists on array elements is deprecated, and doesn't really make much sense. So you can reduce this to:

if ($a{abd} && defined $a{abd}[0])

Replies are listed 'Best First'.
Re^3: restricting values to a nested datastructure
by Marshall (Canon) on Dec 14, 2011 at 15:28 UTC
    Well if we are going to this way, I would use 'exists' for the hash key and 'defined' for the array element, a personal preference.

    #!/usr/bin/perl -w use strict; use Data::Dumper; my %a; if ( exists $a{'abd'} and defined $a{'abd'}->[0] ) { print "yes\n"} print Dumper \%a; __END__ Prints: $VAR1 = {};
    I prefer the arrow notation instead of $a{abd}[0]

    However, Update: not the same! forgot about 0, zero, Ooops

    if ( $a{'abd'} and $a{'abd'}->[0]) { print "yes\n"}
    is the same.

    Whether each term doesn't "exist" or is not "defined" has the same true/false meaning. To prevent the autovivification, each "level" of the hash has to be tested, starting from the first. As long as that is done, it doesn't matter whether 'exists' or 'defined' is tested for subsequent levels.

      However,
      if ( $a{'abd'} and $a{'abd'}->[0]) { print "yes\n"}
      is the same.

      Not really. Array element maybe defined but false. You can't omit defined as easy as exists.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://943558]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others surveying the Monastery: (5)
As of 2024-04-24 06:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found