Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I read a file line by line while modifying lines as needed?
    primarykey
    data
    text
    <p>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.</p> <p>Is there a better way to do this, perhaps some way I can replace single lines as I go along?</p> <p>Right now, my processing code looks like this:</p> <pre><code>while (my $line = &lt;FILE&gt;) { # process line here # ........... print FILE $line; } </code></pre> <p>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.</p> <p>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?</p> <hr> <p><em>Edit:</em></p> <p>Out of the answers I received, both using <code>local $^I</code> and <a href="http://p3rl.org/Tie%3a%3aFile" rel="nofollow"><code>Tie::File</code></a> worked nicely. I ended up going with <code>Tie::File</code> 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.</p> <p>My new code looks like this:</p> <pre><code>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 ....... } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload