With all due respect to those suggesting the hash, both here and in the chatterbox, saints even. I have 2 problems with the hash:
my %actions = (
this => \&this,
that => \&that,
foo => \&foo,
bar => \&bar,
zzz => \&sleepytime);
1. it resembles the original redundant code that was eliminated:
if($in eq "this"){&this}
if($in eq "that"){&that}
if($in eq "foo"){&foo}
if($in eq "bar"){&bar}
if($in eq "zzz"){&zzz}
2. my feeble attempts to implement it do not even succeed, (very possibly due to my own implementation bugs).
The hash plus every variant of code (supplied in replies) to access it gives me:
with use strict: Can't use string ("\&foo") as a subroutine ref while "strict refs" in use
with no strict "refs"; Undefined subroutine main::\&foo
I really want to collapse the kind of repetition represented in my original code, because i'm adding so many options to some scripts that all the ifs (or the hash) are getting ridiculous. I can replace any number of lines related to testing input with ONE:
foreach(@actions){ if($in eq $_){&$_()}}
I did resort to no strict "refs"; and thanks to alakaboo moved that line inside the foreach loop from the top near use strict;.
$in=param('in');
@actions=qw(this that foo bar zzz);
foreach(@actions){ no strict "refs"; if($in eq $_){&$_()}}
I also like using the array like this because it was already there being used for other purposes! How can this be unsafe in practice? The sub name $_ comes from @actions which is predefined and only happens if input matches it. I've tried feeding it other sub names that exist in the script, but it only executes ones that are defined in the array.
|