Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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,




  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (5)
As of 2024-04-16 05:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found