[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] Importing search patterns



> It is possible to take the pattern apart by:
> 
>         $str =~ /\/(.*)\/(.*)/;      #followed by:
>         if ($_ =~ /$1/$2) {}
> 
> but MacPerl baulks at $2 since it expects an operator in that position.
> That problem can be avoided by;
> 
>         if (eval('$_ =~ /$1/'.$2)) {print "Hooray\n"};
> 
> which seems to work, but the use of 'eval' for each line of the file slows
> up execution and also mops up a relatively large amount of memory?

Besides the suggestion that Mattias gave, another option is to use
eval once to create a new subroutine, and call it as much as needed.

eval "sub match { local(\$_) = \@_ if defined \@_;/$1/$2}";

Will create a subroutine that will match what is contained in $1 at
the point the eval is executed, modified by the modifiers contained in
$2 (again at the point of the eval.)

Then you can say:

if(&match) {}
or
if(&match($_)) {}

Then you don't have the heavy eval "" overhead, just the moderate
subroutine call overhead. If you are using more than one variable
regexp, you have to use unique names for each new sub you eval. If you
want a variable number of new subroutines, you can use a variable as
part of the soubroutine name, but you'll probably have to use
typeglobs to access them.

eval "sub match_$var { local(\$_) = \@_ if defined \@_;/$1/$2}";

*match = "match_$var";

if(&match) {}


The perl5 embedded modifiers are a lot slicker though, and faster (as
long as you add the /o modifier to keep them doing the same thing.)