my $rand_position = $positions_ref->[ rand( $#{$positions_ref} ) ]; my $rand_location = $locations_ref->[ rand( $#{$locations_ref} ) ];
You have an off-by-one error on those array subscripts. 'in the kitchen' will never be chosen from @locations and 'reclining' will never be chosen from @positions.
I would write it more like this:
#!/usr/bin/perl use strict; use warnings; my @positions = qw( sitting standing reclining ); my @locations = ( 'at the museum', 'in the woods', 'on the beach', 'in + the kitchen' ); my @drinks = qw( scotch beer coke yoohoo ); 1 while do_it( print_options( \@drinks ), \@positions, \@locations ); sub print_options { my $drinks_ref = shift; for my $i ( 0 .. $#$drinks_ref ) { print $i + 1, ". $drinks_ref->[$i]\n"; } my $selection; do { print 'Choose a number: '; chomp( $selection = <STDIN> ); } until $selection >= 1 && $selection <= @$drinks_ref; return $drinks_ref->[ $selection - 1 ]; } sub do_it { my ( $drink, $positions_ref, $locations_ref ) = @_; my $rand_position = $positions_ref->[ rand @$positions_ref ]; my $rand_location = $locations_ref->[ rand @$locations_ref ]; print "You just drank a $drink $rand_location in the $rand_positio +n position.\n"; if ( $rand_location eq 'on the beach' ) { print "YEEEEEHAAAWWWWWWWWWW!\n"; return 0; } return 1; }
In reply to Re: Repeating an input prompt
by jwkrahn
in thread Repeating an input prompt
by zod
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |