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:  <%-{-{-{-<