Why do you choose a random key to find a random value? =)

pick directly a random value:

DB<127> $self->{exits}= { kitchen => 42, living => 666 , toilet => +"00" } => { kitchen => 42, living => 666, toilet => "00" } DB<128> @values= values %{$self->{exits}} => (666, "00", 42) DB<129> $rand_value = @values[rand @values] => "00" DB<130> $rand_value = @values[rand @values] => 42 DB<131> $rand_value = @values[rand @values] => 42 DB<132> $rand_value = @values[rand @values] => 666

If you still wanna go this way, please DRY.

Replace my $h_ref = $self->{exits} and you can avoid many repetitions of $self->{exits}

DB<134> $h_exits = $self->{exits} => { kitchen => 42, living => 666, toilet => "00" } DB<135> $random_room = $h_exits->{ ( keys %$h_exits )[ rand keys %$h +_exits ] } => "00"

Better readable now! Don't you agree? =)

> this below code does not work

sure unless('exit') is always false.

Cheers Rolf

( addicted to the Perl Programming Language)


In reply to Re: Random Values from Hash with UNLESS statement by LanX
in thread Random Values from Hash with UNLESS statement by cmikel

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.