develooper Front page | perl.beginners | Postings from March 2002

Problems with regex only matching first match on a line.

Thread Next
From:
Tor Hildrum
Date:
March 5, 2002 00:21
Subject:
Problems with regex only matching first match on a line.
Message ID:
B8AA3E1B.5D61%torhildr@mac.com
#!/usr/bin/perl -w
use strict;
use warnings;

print "What file do you want to open?\n";
chomp(my $openfile = <STDIN>);
print "What file do you want to write to?\n";
chomp(my $outfile = <STDIN>);
print "What do you want to replace in the first file?\n";
chomp(my $pattern = <STDIN>);
print "What do you want to replace it with?\n";
chomp(my $replace = <STDIN>);

open (INFILE, "$openfile") or die "Can't open $openfile: $!\n";
open (OUTFILE, ">$outfile") or die "Can't open $outfile: $!\n";

while (<INFILE>) {
        if ($_ =~ /$pattern/i) {
        s/$pattern/$replace/;
        print OUTFILE $_; }
        else {
        print OUTFILE $_; }
}

The script is pretty self-explanatory.
The problem is that it is only replacing the first match on each line.
Is there a way to do this with regex?
I think I could do something like: while($_ =~ /$pattern/i) {replace the
lines}. But, I was wondering if this could be handled within my if-else
structure?

-- 
T.



Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About