Looks like you are seeking a dispatch table
use warnings;
use strict;
use feature 'say';
my %option = (
o1 => sub { say "Code for func1, to run for key 'o1'"; },
o2 => sub { say "Code that should run for input 'o2'"; },
#...
);
my $input = <STDIN>;
chomp $input;
# Dereference the code-reference (run code) associated with $input value
$option{$input}->();
Here sub { ... }
defines an anonymous subroutine and returns a reference to code. Another way to get a code reference is by taking the reference of a named sub, with syntax \&sub-name
. Being a reference it is a (single-valued) scalar type and so it can be used as a hash value.
So when a user supplies o1
what runs is the code in the reference (sub { ... }
) which is the value for the key o1
in the hash, that is $option{o1}
.
The syntax for running code reference is much like derefencing an array or a hash reference
$ar->[0] # dereference array reference, for the first element
$hr->{key} # dereference hash reference, for value for key 'key'
$cr->(LIST) # dereference code reference, to run with arguments in LIST
The scalar variable $cr
here would have the code reference, my $cr = sub { ... }
.