is there a way in perl to change a specific line in a text file without putting the file into an array first?
Apr 26, 2002, 4:50 AM
Veteran / Moderator (18441 posts)
Apr 26, 2002, 4:50 AM
Post #2 of 3
Views: 3710
How do you mean?
If you are trying to edit a file, use something like;
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!
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!
Apr 26, 2002, 5:52 AM
Veteran (19537 posts)
Apr 26, 2002, 5:52 AM
Post #3 of 3
Views: 3692
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
I'd do something like:
print WRITE "New Stuff";
}
else {
print WRITE;
}
You can leave out the chomp if you do it like that.
You might want to put the chomp inside the while loop so you don't end up with blank lines after every row
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.