perl-substitute

merlin's picture

They have: 410 posts

Joined: Oct 1999

helo
i'd like to substitute all '\n' in a file to '\r\n'. it's working fine with the code i wrote but not with big files. i know the problem's because i take all the file into an array...
have a look at my code:

use strict;
my $file = "pathandfilename";
my $line;
open (FILE, "$file") or die "No such file: $file";
my @content = <FILE>
close(FILE);
open(FILE, ">$file");
foreach $line (@content) {
$line =~ s/\n/\r\n/sg;
print FILE $line;
}
close(FILE);
'

now: how do i do that, without reading into @?

thank you for any advice. Smiling

Mark Hensler's picture

He has: 4,048 posts

Joined: Aug 2000

It's been a while since I did any Perl..

Make a copy of the file.
Open the copy.
Open the original.
FOR LOOP
-Read line from copy.
-Make changes.
-Wite line to original.
END LOOP
Close the original.
Close the copy.
Delete the copy.

Mark Hensler
If there is no answer on Google, then there is no question.

merlin's picture

They have: 410 posts

Joined: Oct 1999

seems reasonable.
BUT: how do i read only one line of the file?

merlin's picture

They have: 410 posts

Joined: Oct 1999

i found what i was looking for in my perl cookbook (p. 7.Cool:

open (OLD, "< $file");
open (NEW, "> $tempfile");
while (<OLD>) {
$_ =~ s/\n/\r\n/sg;
print NEW $_;
}
close(OLD);
close(NEW);
'

that's what i love in perl: it's such a tiny piece of code... Smiling

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.