Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: How to print specific word from array/hash?

by johngg (Canon)
on Oct 05, 2016 at 10:27 UTC ( [id://1173329]=note: print w/replies, xml ) Need Help??


in reply to How to print specific word from array/hash?

Others have pointed out that your %colours hash would be much more suitable if it was reversed. However, you can still obtain the colour from the chosen number with the hash as it stands by using keys and grep.

johngg@shiraz:~ > perl -Mstrict -Mwarnings -E ' my %colours = ( blue => q{1}, green => q{2}, red => q{3}, pink => q{4}, purple => q{5}, ); my @numbers = qw{ 1 2 3 4 5 }; my $pick = $numbers[ int rand @numbers ]; say qq{Number $pick chosen}; my( $colour ) = grep { $colours{ $_ } eq $pick } keys %colours; say qq{Colour is $colour};' Number 2 chosen Colour is green

Of course, building the hash the right way in the first place is by far the best approach.

Cheers,

JohnGG

Replies are listed 'Best First'.
Re^2: How to print specific word from array/hash?
by AnomalousMonk (Archbishop) on Oct 05, 2016 at 12:22 UTC

    And of course, this approach allows a number to represent more than one color, if this is necessary:

    c:\@Work\Perl\monks>perl -wMstrict -le "my $color = 7; ;; my %colors = qw(blue 1 green 7 red 3 pink 7 purple 6); ;; my @picked = grep { $colors{$_} eq $color } keys %colors; print qq{color(s) picked by $color: @picked}; " color(s) picked by 7: green pink


    Give a man a fish:  <%-{-{-{-<

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (2)
As of 2024-04-25 05:55 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found