Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Repeating an input prompt

by jwkrahn (Abbot)
on Nov 28, 2008 at 22:14 UTC ( [id://726685]=note: print w/replies, xml ) Need Help??


in reply to Repeating an input prompt

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; }

Replies are listed 'Best First'.
Re^2: Repeating an input prompt
by zod (Scribe) on Nov 28, 2008 at 23:05 UTC
    Thanks for the critique. I don't quite understand this line, though:
    until $selection >= 1 && $selection <= @$drinks_ref;
    Wouldn't that always be true if you input 1 - 4 ? Can you elaborate on that a little? thanks.

      I put that in to verify that the selection was a number in the range 1 - 4.

        Got it. When I first looked at it, I was thinking the do..until loop was still controlling the 'outer' loop..like in my original code. Now I see that you moved that to a while loop.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2024-03-19 06:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found