in reply to Match, Capture and get position of multiple patterns in the same string
#!/usr/bin/perl use strict; my $string = "CATINTHEHATWITHABAT"; my $regex = '\wAT'; my @matches = (); while ($string =~ /($regex)/gi){ my $match = $1; my $length = length($&); my $pos = length($`); my $start = $pos + 1; my $end = $pos + $length; my $hitpos = "$start-$end"; push @matches, "$match found at $hitpos "; } print "$_\n" foreach @matches;
The difference is that a foreach loop builds the list before you start, whereas the while loop re-executes the expression each time. This means that you are clobbering $& and friends at the start of your foreach loop, but using a while loop means the values are fresh.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Match, Capture and get position of multiple patterns in the same string
by richardwfrancis (Beadle) on Nov 13, 2009 at 02:08 UTC | |
by moritz (Cardinal) on Nov 13, 2009 at 07:42 UTC | |
by richardwfrancis (Beadle) on Nov 13, 2009 at 08:33 UTC | |
by moritz (Cardinal) on Nov 13, 2009 at 08:57 UTC | |
by kennethk (Abbot) on Nov 13, 2009 at 16:03 UTC | |
by richardwfrancis (Beadle) on Nov 16, 2009 at 06:56 UTC |