Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: How to ignore and retrieve certain values from text file which is to be split into multiple HTML files with tables?

by Athanasius (Archbishop)
on Apr 23, 2016 at 03:40 UTC ( [id://1161290]=note: print w/replies, xml ) Need Help??


in reply to How to ignore and retrieve certain values from text file which is to be split into multiple HTML files with tables?

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,

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1161290]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (7)
As of 2024-03-28 10:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found