Hello perly_white, and welcome to the Monastery!
The requirements are not entirely clear. If filenames can appear out-of-order in the input file:
Filename1 Item1 - Answer Filename2 Item1 - Answer Filename1 Item2 - Answer
then you will need to either (1) read the whole file into a suitable data structure before writing tables, or (2) keep track of each open file, associating the filename with the handle. For (1), you could use a hash of arrays1 like this:
my %files; $files{Filename1} = [ 'Item1 - Answer' ]; push @{ $files{Filename1} }, 'Item2 - Answer'; ...
For (2), you would need a simple hash with filename/filehandle key/value pairs.
However, it appears from the question that you know in advance that filenames cannot appear out-of-order. If that’s the case, the following skeleton script should provide a straightforward approach:
use strict; use warnings; use autodie; # open the data file for reading my $data_filename = 'data.txt'; open my $in_fh, '<', $data_filename; # output files my $current_filename = ''; my $out_fh; while (<$in_fh>) # process one line of data { my ($new_filename, $item) = split ' ', $_, 2; if ($new_filename ne $current_filename) { finalize_table($out_fh) if defined $out_fh; open $out_fh, '>', $new_filename; $current_filename = $new_filename; initialize_table($out_fh); } add_row($out_fh, $item); } close $in_fh; finalize_table($out_fh) if defined $out_fh; sub initialize_table { ... } sub add_row { ... } sub finalize_table { my ($fh) = @_; # ... close $out_fh; }
Update: 1See perldsc#HASHES-OF-ARRAYS.
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
|
|---|