how to count matches?

G

Geoff Cox

Hello

I want to use regex to find/replace say <jim> with $num-fred<jim> so
that $num increase by 1 for each occurrence.

It might that there are 2 of <jim> on a line so my code below is not
working - how should I change it? Clues please!

$num = 1;

if ($line =~ /<jim>/) {
my $orig = "<jim>";
my $new = "$num-jim";
$line =~ s/$orig/$new/g;
$num++;
}

Thanks

Geoff
 
J

John Bokma

Geoff said:
Hello

I want to use regex to find/replace say <jim> with $num-fred<jim> so
that $num increase by 1 for each occurrence.

It might that there are 2 of <jim> on a line so my code below is not
working - how should I change it? Clues please!

$num = 1;

if ($line =~ /<jim>/) {
my $orig = "<jim>";
my $new = "$num-jim";
$line =~ s/$orig/$new/g;
$num++;

Not tested: s{$orig}{ $num++ . "-jim" }ge;

note the e.

Also note that the first part of your posting and your actual code are in
disagreement.
 
A

Arndt Jonasson

Geoff Cox said:
I want to use regex to find/replace say <jim> with $num-fred<jim> so
that $num increase by 1 for each occurrence.

It might that there are 2 of <jim> on a line so my code below is not
working - how should I change it? Clues please!

$num = 1;

if ($line =~ /<jim>/) {
my $orig = "<jim>";
my $new = "$num-jim";
$line =~ s/$orig/$new/g;
$num++;

Use the 'e' modifier:

if ($line =~ /<jim>/) {
my $orig = "<jim>";
$line =~ s/$orig/$num++ . "-jim"/ge;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top