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'


In reply to Re: Re: Conditional idiom : "if X equals Y or Z" ?? by belden
in thread Conditional idiom : "if X equals Y or Z" ?? by George_Sherston

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.