Re: why the loop-break after pattern-matching



On 01/01/12 08:08, dn.perl@xxxxxxxxx wrote:

Well, apparently in a scalar context, the 'g' option remembers where
it had left off the pattern-matching the last time and takes it up
from that point. !!!

If I had a pound for every time the very act of asking for help on a problem prompts one to find the solution ...

But I wouldn't code "g" at all in this case (unless your real data contains multiple copies of the pattern), and my practice is to use $1 (and $2, $3 etc if necessary) to collect the results of the matches rather than $&. Also, what are you going to do if your pattern doesn't match?

I amused myself on this Neew Year's morning by re-writing your code a little; I'm not an experienced Perl coder so having made suggestions to you I'm open to them myself.

#!/usr/bin/perl
use strict;
use warnings;

my $counter = 0;
while ( my $line = <DATA> ) {
$counter++;
if ( $line =~ /pattern( \S+-\d+)+/i ) {
print "Log is $1\n";
}
else {
chomp $line;
warn "Bad input line no $counter: '$line'\n";
}
}
print "$counter lines read\n";

__DATA__
[pattern number-405] check
Rubbish
[pattern number-406] check
[pattern number-407] check


--

Henry Law Manchester, England
.