Pattern remembering and replacing

S

Steve Hémond

Hi people,

I am following a very good Perl tutorial and I have reached this exercise :

....
"Your current program should count lines of a file which contain a certain
string. Modify it so that it counts lines with double letters (or any other
double character). Modify it again so that these double letters appear also
in parentheses. For example your program would produce a line like this
among others:

023 Amp, James Wa(tt), Bob Transformer, etc. These pion(ee)rs conducted many

Try to get it so that all pairs of letters are in parentheses, not just the
first pair on each line."
....


Here is my Perl program :

#!/usr/bin/perl -w

$file = '/home/shemond/Perl/electricity.txt';
open (INFO, $file);
$a = 1;
while ($line = <INFO>)
{

if ($line =~ /(\w)\1/)
{
$line =~ s/(\w)\1/($1)/g;
print "$a $line";
$a++;
}
else
{
print " $line";
}
}


Here is what my programs outputs :
023 Amp, James Wa(t), Bob Transformer, etc. These pion(e)rs conducted many

As you can see, my program is able to match doubled-character (although I'm
not sure if it's a proof match).

The problem is it prints only one character, not both characters.

I surely misundertand Pattern Remembering using the \1 variable.

Can anyone explain what I am doing wrong? I need more explanations about
pattern remembering ...

Thanks a lot for your answers!

Steve
 
J

John J. Trammell

Try to get it so that all pairs of letters are in parentheses, not
just the first pair on each line."
...

#!/usr/bin/perl -w

use strict; # let Perl do the work
$file = '/home/shemond/Perl/electricity.txt';
open (INFO, $file);

open(INFO,$file) || die "can't open $file: $!";
$a = 1;
while ($line = <INFO>)
{

if ($line =~ /(\w)\1/)
{
$line =~ s/(\w)\1/($1)/g;

One solution (untested):

$line =~ s/(\w)\1//$1$1/g;

another solution (untested):

$line =~ s/((\w)\2)//$1/g;
print "$a $line";
$a++;
}
else
{
print " $line";
}
}

JT
 

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

No members online now.

Forum statistics

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

Latest Threads

Top