in reply to Re: use slack;
in thread use slack;

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.

Replies are listed 'Best First'.
Re: use slack;
by Dominus (Parson) on Dec 20, 2000 at 02:51 UTC
    Says epoptai:
    > Can't use string ("\&foo")
    That's because your hash has
    that => '\&that',
    when it should have
    that => \&that,
      After some discussion in the ChatterBox, it was revealed that epoptai was actually using qw// to create his hash:
      %hash = qw/ this \&this that \&that /;
      He was suitably abashed at his mistake. :)
        After some confusion it is revealed by Dominus that I fell prey to the cargo cult by cutting and pasting a misquoted hash. I appreciate the test and assure you it won't happen again ;-)