Gossamer Forum
Home : General : Perl Programming :

write file in 'while'

Quote Reply
write file in 'while'
is there a way in perl to change a specific line in a text file without putting the file into an array first?
Quote Reply
Re: [robyone] write file in 'while' In reply to
How do you mean?

If you are trying to edit a file, use something like;

Code:
open(READ, "readfile.txt") || die "Unable to read file...error: $!";
open(WRITE, "newfile.txt") || die "Unable to read file...error: $!";

chomp;
while (<READ>) {

$line = $_;
if ($line =~ /whatever you want to replace/) {
$line = "new value";
}

print WRITE "$line\n";
}

close(READ);
close(WRITE);

Obviously you need the 'error' sub, and make it so it passes th variabes along to the sub (with shift). That code is not guaranteed to work...I'm al itttle rusty on my Perl code ;)

Andy (mod)
andy@ultranerds.co.uk
Want to give me something back for my help? Please see my Amazon Wish List
GLinks ULTRA Package | GLinks ULTRA Package PRO
Links SQL Plugins | Website Design and SEO | UltraNerds | ULTRAGLobals Plugin | Pre-Made Template Sets | FREE GLinks Plugins!
Quote Reply
Re: [Andy.] write file in 'while' In reply to
Hmm interesting.

You might want to put the chomp inside the while loop so you don't end up with blank lines after every row Cool

I'd do something like:

Code:
if (/whatever you want to replace/) {
print WRITE "New Stuff";

}
else {
print WRITE;
}

You can leave out the chomp if you do it like that.

Last edited by:

Paul: Apr 26, 2002, 5:55 AM