Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: STDIN method?

by insensate (Hermit)
on Oct 17, 2002 at 20:40 UTC ( [id://206135]=note: print w/replies, xml ) Need Help??


in reply to STDIN method?

I always like using a hash:
use strict; my %hash=(1=>"Turkey",2=>"Goat",3=>"Fish"); print "choose 1:\n"; for(sort keys %hash){ print "$_=$hash{$_}\n"; } print "Choice: "; my $ans=<STDIN>; chomp $ans; print "Invalid Answer!" unless exists $hash{$ans}; print "You chose $hash{$ans}\n";
This way you only have to change the hash as your selection alternatives change.
-Jason

Replies are listed 'Best First'.
Re: Re: STDIN method?
by charnos (Friar) on Oct 17, 2002 at 20:56 UTC
    That makes the most sense to me too. Plus if you need to scale up your switch statement, it's easy with a hash!
    $hash{1} = sub {print "You chose turkey";}; $hash{2} = sub {print "You chose Goat;"; print "..ew";}; for (keys %hash) { &{$hash{$_}}; }
    ..Obviously for just picking what to print, you're making work for yourself, but if you need to accomplish more than that (which is usually the case), it can save time (without a million elsifs cluttering your code).

Log In?
Username:
Password:

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

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

    No recent polls found

    Notices?
    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.