Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re^3: Default Hash Key

by mrons (Beadle)
on May 02, 2008 at 05:21 UTC ( [id://684097]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Default Hash Key
in thread Default Hash Key

Just be careful about $description{foo} that evaluate to false:
use strict; use warnings; my %description = ( a => 'a vowel', b => 'a consonant', 0 => '0', default => 'not in the alphabet' ); for my $char (qw/a b c 0/) { my $d = $description{$char} || $description{default}; print("$char is $d\n"); }

Replies are listed 'Best First'.
Re^4: Default Hash Key
by EvanCarroll (Chaplain) on May 02, 2008 at 14:51 UTC
    Which is why god invented the '//' operator -- most definitely a better choice than '||' in this context.


    Evan Carroll
    I hack for the ladies.
    www.EvanCarroll.com
Re^4: Default Hash Key
by matze (Friar) on May 03, 2008 at 12:58 UTC
    Which is where the exists used in the first two original replies to the OP comes in handy...

    Because of things like this, I find myself using defined and exists a lot when writing code. It may be more verbose but better safe than sorry... I hope I'm not too much of a Captain Obvious :)
Re^4: Default Hash Key
by Anonymous Monk on May 04, 2008 at 17:10 UTC
    That problem is avoided in Perl 5.10.0 with my $d = $description{$char} // $description{default}; # check for undefined rather than false As for getting one's head around the logical or, it's really quite simple: $a || $b || $c || ... yields the first value that is true (or false if none are). Perl didn't invent it; it's a common operator in many languages, dating back to Snobol, I think.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (2)
As of 2024-04-26 00:57 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found