Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

Re^3: Default Hash Key

by mrons (Sexton)
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"); }

Comment on Re^3: Default Hash Key
Download Code
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 the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (6)
As of 2015-11-27 04:50 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (718 votes), past polls