in reply to optimized switch case

A couple of thoughts:
$_ = &fetch_input; $picked{$_}++ foreach split //; &do_a if $picked{a}; &do_b if $picked{b}; ... # or, simpler: $_ = &fetch_input; &do_a if /a/; &do_b if /b/; ...

Replies are listed 'Best First'.
Re: Re: optimized switch case
by clintp (Curate) on Jan 03, 2002 at 21:35 UTC
    # Or more maintainable! %options=( a => sub { do_this() or that() }, b => \&do_that, c => sub { do_nut() }, ); foreach(split(//, &fetch_input)) { &{$options{$_}} if exists $options{$_}; }
Re (tilly) 2: optimized switch case
by tilly (Archbishop) on Jan 07, 2002 at 16:31 UTC
    I suggest not getting people in the habit of using the &foo syntax for calling functions because of the implicit argument passing that they are probably not aware of. Even if you know the gotchas, a lot of people do not.

      tilly, could you please clarify? Are you referring to the passing of the package name or object reference when calling a function like $bar->foo()? Using the ampersand bypasses this behavior, so I'm not sure what you're getting at.

        I am referring to the fact that, as documented in perlsub, calling &foo shares @_ with the current package. Calling it with parentheses gives it its own argument list. The following demo script may give you an idea what this means:
        #! /usr/bin/perl use strict; use vars qw($indent); $indent = ''; print "Here is how things go without an &\n"; demo_no_amp(1..5); <STDIN>; print "Here is how they go with an &\n"; demo_with_amp(1..5); <STDIN>; print "And with explicit argument passing\n"; demo_explicit_args(1..5); <STDIN>; print "Done\n"; sub demo_no_amp { local $indent = $indent . " "; while (@_) { my $arg = shift; print $indent, "Without &, '$arg'\n"; demo_no_amp(); } } sub demo_with_amp { local $indent = $indent . " "; while (@_) { my $arg = shift; print $indent, "With &, '$arg'\n"; &demo_with_amp; } } sub demo_explicit_args { local $indent = $indent . " "; while (@_) { my $arg = shift; print $indent, "With explicit args, '$arg'\n"; demo_explicit_args(@_); } }
        Puzzle out why those three cases are so different and you will understand why I think the second one is dangerous.