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

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'