while (my @parsed = &parseInput) {
&dispatch(@parsed);
}
sub parseInput {
...
my @parsed = split $inp;
return 0 if $parsed[0] eq `q`;
...
}
####
sub dispatch {
my $cmd = shift;
try { eval( '&' . $cmd . '(' . join ',', @_ . ');' ); }
catch { print STDERR "Unrecognised command $cmd\n"; }
# the above is a non-GUI example which would need adaptation
}
##
##
c:\@Work\Perl\monks>perl -wMstrict -le
"BEGIN {
;;
my %dispat = (
'foo' => sub { print 'Fooing: ', qq{(@_)}; },
'bar' => \&bar,
);
;;
sub dispatch {
my $cmd = shift;
;;
$cmd = lc $cmd;
if (not exists $dispat{$cmd}) {
print qq{do not know how to '$cmd'};
return;
}
$dispat{$cmd}->(@_);
}
}
;;
while (my @parsed = parseInput()) {
dispatch(@parsed);
}
;;
sub parseInput {
my $inp = <>;
chomp $inp;
my @parsed = split ' ', $inp;
return if lc($parsed[0]) eq 'q';
return @parsed;
}
;;
sub bar { print 'Baring: ', qq{(@_)}; }
"
foo
Fooing: ()
bar
Baring: ()
foo 1 2 3
Fooing: (1 2 3)
bar x xyzzy
Baring: (x xyzzy)
boff
do not know how to 'boff'
Q
##
##
c:\@Work\Perl\monks>perl -wMstrict -le
"dispatch(qw(foo 9 8 7 6));
;;
sub dispatch {
my $cmd = shift;
my $evil_string = '&' . $cmd . '(' . join ',', @_ . ');';
print qq{>>$evil_string<<};
}
"
>>&foo(4);<<
c:\@Work\Perl\monks>perl -wMstrict -le
"dispatch(qw(foo 9 8 7 6));
;;
sub dispatch {
my $cmd = shift;
my $evil_string = '&' . $cmd . '(' . join(',', @_) . ');';
eval $evil_string;
}
;;
sub foo { print qq{'in Foo:' (@_)} }
"
'in Foo:' (9 8 7 6)