I want to find a file for a string, and then get the offsets for all matches. The contents of the file are as follows:
sometext sometext AAA sometext AAA AAA sometext
I read the whole file in the line $text , and then execute the regex for AAA as follows:
if($text =~ m/AAA/g) { $offset = $-[0]; }
This will give an offset of only one AAA . How can I get the offset from all matches?
I know that we can get all matches in an array using syntax like this:
my @matches = ($text =~ m/AAA/g);
But I need a biased string without matching.
I am currently using the following code to get the offsets of all matches:
my $text= "sometextAAAsometextAAA"; my $regex = 'AAA'; my @matches = (); while ($text =~ /($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;
But is there an easier way?
source share