Notice I had to toss in an extra parameter- a reference to a subroutine.sub in { my ($coderef)= shift(@_); my ($match)= shift(@_); my (@vals)= @_; for ( @vals ) { $coderef->($match) if /$match/ } }
Another way to write this up is
Shrug, it's another way, I guess.sub in { my ($coderef)= shift(@_); my ($match)= shift(@_); my %dispatch = map { $_ => $coderef } @_; if ( exists $dispatch{$match} ) { $dispatch->($match); } }
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." :)
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 ;)#!/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
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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |