Gossamer Forum
Home : General : Perl Programming :

Passing pattern to subroutine

Quote Reply
Passing pattern to subroutine
Not following why this matches everything, or
if it's the best way, can someone advise?:

@array1=('Bill', 'Betty', 'Fred', 'Freda')

sub MatchIt($stringtest){
foreach(@array1){
if($_ =~ $stringtest){
print "Match: $_\n";
}
}
}

&MatchIt(/re/);
Quote Reply
Re: Passing pattern to subroutine In reply to
A couple problems:

sub MatchIt($stringtest) {

Hmm.. Not the way to pass parameters in perl. If you call a subroutine &MatchIt($param1), the parameter list gets stored in the array @_. It's quite common to do:

sub MatchIt {
my $stringtest = shift; # Get's the first parameter;
...
}

or

sub MatchIt {
($param1, $param2, $param3) = @_; # Get multiple parameters.
...
}

Another thing, when you call: &MatchIt(/re/), you are not passing the string '/re/', but rather the result of the regular expression /re/. Here's how I would write the subroutine:

@array1=('Bill', 'Betty', 'Fred', 'Freda');

sub MatchIt {
my $test = shift;
foreach (@array1) {
/$test/ and print "Matched: $_\n";
}
}
&MatchIt('re');

Note: if you just do /$test/ it assumes you are working on the $_ variable. It's the same thing as saying $_ =~ /$test/.

Hope that helps,

Alex
Quote Reply
Re: Passing pattern to subroutine In reply to
Much thanks Alex,
Teaches me to mix my C with Perl, as in sub Blah ($parameter) Wink
Also helped me on a few other levels, i kind of knew if =~ $_ was redundant, and introduced me to using shift in arrays.