In Perl, I’m trying to read a file line by line and process each line, modifying it as required.
So far, the only way I’m reading to be able to do this is read the file into an array, modify each element of the array as needed, then when it’s finished, output it back to the file.
Is there a better way to do this, perhaps some way I can replace single lines as I go along?
Right now, my processing code looks like this:
while (my $line = <FILE>)
{
# process line here
# ...........
print FILE $line;
}
My code seems to be very close, except that it’s replacing one line after the line I’m currently in, so it seems that if I could back the file pointer up by one line, it would write to the correct place in the file.
Am I on the right track? What would I need to do from here to back up the file pointer so it writes to the same line I’m reading from?
Edit:
Out of the answers I received, both using local $^I and Tie::File worked nicely.
I ended up going with Tie::File so I wouldn’t have to print out every line of the file. This way if something happens midway through the script, my file won’t be messed up.
My new code looks like this:
use Tie::File;
chomp(my $filename = $ARGV[0]);
tie my @array, 'Tie::File', $filename or die $!;
foreach my $line(@array)
{
# ...... line processing happens here .......
# ...... $line is automatically written to file if $line is changed .......
}
I don’t think it’s a good idea to read from a file and write to it at the same time like you do.
You could use
Tie::File. It ties the lines of a file to an array. You can modify the array as you need which in turn modifies the file transparently in the background.