in reply to use slack;

Because you're still doing the same thing -- using a string as the name of a function.

Here's the hash of subroutine references:

my %actions = ( this => \&this, that => \&that, foo => \&foo, bar => \&bar, zzz => \&sleepytime, ); # ooh, tricky foreach (@user_actions) { if (defined(my $sub_ref = $actions{$_})) { $sub_ref->(); } }

Replies are listed 'Best First'.
markjugg: re: use slack;
by markjugg (Curate) on Dec 19, 2000 at 21:16 UTC
    Since the original intent appeared to be to run just one subroutine, you can probably even lose the subroutine in chromatics example:
    my $in = param('in'); my %actions = ( this => \&this, that => \&that, foo => \&foo, bar => \&bar, zzz => \&sleepytime, ); defined(my $sub_ref = $actions{$in}) && $sub_ref->() ;
    -mark
Re: Re: use slack;
by epoptai (Curate) on Dec 20, 2000 at 01:26 UTC
    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.
      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. :)