why the loop-break after pattern-matching

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

Here is the code:

use strict ;
use warnings ;

my $counter = 1;
my $log = "[pattern number-405] check" ;
print "log is:$log\n" ;
while ( $log =~ /(pattern)( \S+-\d+)+/ig )
    my $match = $& ;     ## $& is the str yielded by the last pattern
    $match =~ s/^\S+ // ; # remove first word
    print "match is $match\n" ;
    last if $counter++ > 25 ;
print "log is:$log\n" ;
# - - - - - - - -  - - -

Why does the loop break after just the first pass? I would expect the
while condition to never change in this patch.

Re: why the loop-break after pattern-matching

Quoted text here. Click to load it

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. !!!

Re: why the loop-break after pattern-matching

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

Quoted text here. Click to load it

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

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.

use strict;
use warnings;

my $counter = 0;
while ( my $line = <DATA> ) {
   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";

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


Henry Law            Manchester, England

Site Timeline