Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: how to add conditionals to hash and stdin.

by choroba (Cardinal)
on Mar 13, 2014 at 15:42 UTC ( [id://1078189]=note: print w/replies, xml ) Need Help??


in reply to how to add conditionals to hash and stdin.

You are after a dispatch table.
#!/usr/bin/perl use warnings; use strict; my @actions = qw( add subtract quit ); my %dispatch = ( add => sub { my ($x, $y) = map int rand 10, 1, 2; print "$x + $y = ", $x + $y, "\n"; }, subtract => sub { my ($x, $y) = map int rand 10, 1, 2; print "$x - $y = ", $x - $y, "\n"; }, quit => sub { exit }, ); while (1) { for my $idx (0 .. $#actions) { print "$idx) $actions[$idx]\n"; } chomp(my $choice = <>); $choice = $actions[$choice] if $choice =~ /^[0-9]$/; if (exists $dispatch{$choice}) { $dispatch{$choice}->(); next } print "Invalid option.\n"; }
لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (5)
As of 2024-03-29 13:44 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found