I preferred , in this instance , to work with an array, and to check the contents of the array. This is because further down the track of this program I want to manipulate the contents of some lines in the array, and add additional lines to the arrays.
It might still be worth considering doing the work in one pass while reading the file line-by-line. While 5174 lines is probably still small enough to fit into memory, if your file does grow, performance might suffer, and you might end up having to rewrite the program. The general approach would be to use a while (<$filehandle>) loop to read the file line-by-line and keep track of the current line number yourself or with Perl's special variable $.. For each line you read, either modify it or don't, and print it back out. When you hit the line number where you want to insert records, use additional print statements in an if to do so.
But of course I also understand the simplicity of just manipulating an array. Note that the core module Tie::File might be worth looking at, it will give you a normal-looking Perl array, but behind the scenes it is actually accessing the lines of the file, while keeping only some of them in memory. You can then do all your normal Perl array operations on it, including splice to remove and insert records, and the changes will be made to the file. While the module isn't necessarily the fastest when it comes to writing to the file, it does have the advantage to give you a pretty transparent interface and you don't have to worry about memory management.
| [reply] [d/l] [select] |
Hi, see my second example, showing how to get an array of the lines with Path::Tiny::lines() (which you should probably use with the chomp option if you are planning to do more than simply print the lines):
use strict; use warnings;
use Path::Tiny;
my $filename = "foobar.txt";
my @lines = path( $filename )->lines({ chomp => 1 });
# done!
The way forward always starts with a minimal test.
| [reply] [d/l] [select] |