replace some words in special field in a line.

replace some words in special field in a line.

am 12.12.2004 10:18:21 von Wang Penghui

Hi all:

I am a newbie with perl. I have met a pazzle now.
I have a file with thousands of lines. And which line has four fields.
They are separated by a "\t".
Such as:
================file==================
line1first line1second line1third line1fourth
line2first line2second line2third line2fourth
line3first line3second line3third line3fourth
........
Now i want to replace some words in the fourth field. While the first
three fields stay here as before.
I have writen a little code about it. Here is it:

open (ZH,"file") || die "could not open filename!"
@instead=split(/\t/,);
close (ZH) || die "could not close filename!"
open (ZH,">file") || die "could not open filename!"
foreach (@instead) {
s/original/changed/g
print ZH $_;
};
close (ZH) || die "could not close filename!"

This script would replace all the words matched in each field. But it's
not what i want to get.
Anyone could pick me up?
Thanks in advance!

Wang Penghui

Re: replace some words in special field in a line.

am 12.12.2004 10:35:01 von Matt Garrish

"Wang Penghui" wrote in message
news:322gmhF3f6sgrU2@individual.net...
> Hi all:
>
> I am a newbie with perl. I have met a pazzle now.
> I have a file with thousands of lines. And which line has four fields.
> They are separated by a "\t".
> Such as:
> ================file==================
> line1first line1second line1third line1fourth
> line2first line2second line2third line2fourth
> line3first line3second line3third line3fourth
> .......
> Now i want to replace some words in the fourth field. While the first
> three fields stay here as before.
> I have writen a little code about it. Here is it:
>
> open (ZH,"file") || die "could not open filename!"
> @instead=split(/\t/,);
> close (ZH) || die "could not close filename!"
> open (ZH,">file") || die "could not open filename!"
> foreach (@instead) {
> s/original/changed/g
> print ZH $_;
> };
> close (ZH) || die "could not close filename!"
>

The above code doesn't compile and even if it did it would only read one
line of the file (not to mention the total lack of whitespace, failure to
use strictures and warnings, etc., etc., etc.). Please post real code in the
future.

With regards to your problem, take a look at Text::CSV_XS.

Matt