Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Re^3: Default Hash Key

by mrons (Beadle)
on May 02, 2008 at 05:21 UTC ( #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.
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?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://684097]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (4)
As of 2018-06-22 21:48 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (124 votes). Check out past polls.