Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: Conditional idiom : "if X equals Y or Z" ??

by axelrose (Scribe)
on Jun 11, 2002 at 19:25 UTC ( #173631=note: print w/replies, xml ) Need Help??


in reply to Conditional idiom : "if X equals Y or Z" ??

in SQL one would write
... where Action in ("GetAll", "Make", "MakeOnly" )
This brings me to the idea to write
if( in( $Action, "GetAll", "Make", "MakeOnly" ) ) { ... } sub in { ... }
What do you think?

Replies are listed 'Best First'.
Re: Re: Conditional idiom : "if X equals Y or Z" ??
by belden (Friar) on Jun 12, 2002 at 23:44 UTC
    Your in looks like it might have a for loop inside it. Here's one way to write that up.

    sub in { my ($coderef)= shift(@_); my ($match)= shift(@_); my (@vals)= @_; for ( @vals ) { $coderef->($match) if /$match/ } }
    Notice I had to toss in an extra parameter- a reference to a subroutine.

    Another way to write this up is

    sub in { my ($coderef)= shift(@_); my ($match)= shift(@_); my %dispatch = map { $_ => $coderef } @_; if ( exists $dispatch{$match} ) { $dispatch->($match); } }
    Shrug, it's another way, I guess.

    What do you think?
    I think that I can't look at your sub 'in' without either thinking, "Hey, this has a for loop inside it", or "Hey, this probably uses a dispatch table." :)

    #!/usr/bin/perl use strict; use warnings; sub in_dispatch { my ($coderef)= shift(@_); my ($match)= shift(@_); my %dispatch = map { $_ => $coderef } @_; if ( exists $dispatch{$match} ) { $dispatch{$match}->($match); } } sub in_array { my ($coderef)= shift(@_); my ($match)= shift(@_); my (@vals)= @_; for ( @vals ) { $coderef->($match) if /$match/ } } my $code = sub { my ($pal)= shift(@_); print "Hello $pal!\n" ; }; my @pals = qw(Dick Jane Spot Samuel); in_dispatch($code, 'George', @pals); # no output in_dispatch($code, 'Jane', @pals); # Hello Jane! in_list($code, 'Dick', @pals); # Hello Dick! in_list($code, 'Rover', @pals); # no output
    But before you go using this for any life support systems, make sure you don't mind how both subs handle 'Sam' as the item to test ;)

    Update Added #! line

    blyman
    setenv EXINIT 'set noai ts=2'

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://173631]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (2)
As of 2023-12-10 08:09 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What's your preferred 'use VERSION' for new CPAN modules in 2023?











    Results (39 votes). Check out past polls.

    Notices?