#!/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.
In reply to Re: Match, Capture and get position of multiple patterns in the same string
by kennethk
in thread Match, Capture and get position of multiple patterns in the same string
by richardwfrancis
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |