in reply to Re^2: I have a list expanding when I don't want it to
in thread I have a list expanding when I don't want it to

Why not leave %list as is ?
sub random { my ($user_input, $list) = @_; if ($user_input =~ /(?:help|options)/) { my $keys = join ", ",keys %$list; return "Your options are: $keys, or all."; } elsif ($user_input eq 'dump') { use Data::Dumper; return Dumper($list); } else { my @values=(); if ($user_input eq 'all'){ @values = map { @$_ } values %$list; } else { @values = values @$list{$user_input}; } return (shuffle @values)[0]; } }
poj

Replies are listed 'Best First'.
Re^4: I have a list expanding when I don't want it to
by Lady_Aleena (Priest) on Nov 23, 2014 at 08:28 UTC

    poj, I did it your way (with my own additions) by not creating two new hash keys.

    use List::Util qw(shuffle); sub random { my ($user_input, $list) = @_; my $random_thing; if ($user_input && $user_input =~ /(?:help|options)/) { my $keys = join(', ', keys %{$list}); $random_thing = "Your options are: $keys, or all."; } elsif ($user_input && $user_input eq 'list') { $random_thing = $list; } else { my @random_list; # The following gets the keys to randomize instead of $list->{'key +s'}. if ($user_input && $user_input eq 'keys') { @random_list = keys %{$list}; } # The following gets the entire list to randomize instead of $list +->{'all'}. elsif (!$user_input || $user_input eq 'all' ) { @random_list = map { @$_ } values %{$list}; } else { @random_list = shuffle(@{$$list{$user_input}}); } $random_thing = $random_list[rand @random_list]; } return $random_thing; }
    No matter how hysterical I get, my problems are not time sensitive. So, relax, have a cookie, and a very nice day!
    Lady Aleena
Re^4: I have a list expanding when I don't want it to
by Lady_Aleena (Priest) on Nov 20, 2014 at 09:48 UTC

    poj, can you accept I didn't think about doing it your way? Also, you don't have keys available to random generate nor did you make 'all' the default if no $user_input. I sometimes want a more general result which is why I have a keys list. I will give this a big think and maybe incorporate some of this. Thanks!

    No matter how hysterical I get, my problems are not time sensitive. So, relax, have a cookie, and a very nice day!
    Lady Aleena