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

Re: [MacPerl] passing regexp to routine



At 12:20 AM 6/10/98 +0200, you wrote:
>At 18.36 +0200 98-06-09, Brian "L." Matthews wrote:
>>Yes: last if /$regex/o;
>>
>>The trailing o tells perl to compile the expression once instead of every
>>time through the loop. Being *every* expression has to be compiled at least
>>once, /$regex/o isn't any slower than /hard coded regex/.
>
>That's OK if you always want to call the subroutine once, but if you call
>the same subroutine again with another $regex string, perl will continue
>using the old compiled regex, because of the /o. It means once, not once
>per subroutine call.
>
>To really recompile the regex only when calling the subroutine, we could
>use the fact that the null pattern ($var =~ //;) defaults to the last
>successfully executed regex.
>

OK, so given that my original attempt (slightly modified at the advice of
many list members) was:

read_until('#EOF');

sub read_until { my($endpat) = @_;
$line = <STDIN>;
while ($line !~ /$endpat/) {
	print $line;
	$line = <STDIN>;
	}
} read_until()

we could avoid the constant re-compilation of the regular expression in the
"while" condition, but still get a recompilation for each call to
read_until() by "unrolling" the first iteration of the while loop, obtaining:

sub read_until { my($endpat) = @_;
$line = <STDIN>;
if ($line !~ /$endpat/) {
	print $line;
	$line = <STDIN>;
	while ($line !~ //) {
		print $line;
		$line = <STDIN>;
		}
	}
}

Does anyone see a problem with this solution - i.e. is it 1) equivalent to
the original, and 2) does it accomplish the desired single reg exp
compilation per call to read_until()?

BTW, "unrolling" a loop just makes use of the fact that the following
should be logically equivalent:

while <condition> {
	<do something>
	}

... and ...

if <condition> {
	<do something>
	while <condition> {
		<do something>
		}
	}


***** Want to unsubscribe from this list?
***** Send mail with body "unsubscribe" to mac-perl-request@iis.ee.ethz.ch