Hello bestfa, and welcome to the Monastery!

Please put your code in <code> tags — see Markup in the Monastery

If you’re reading the input file line-by-line, you’ll want to create filehandles on the fly, one for each unique data type. And when you open each output file, you’ll have to open it for appending (>>), not writing (>), to allow successive iterations of the loop to add new entries to the end of the file.

The data structure you need is a hash, not an array. Specifically, a hash that maps output file names data types to their corresponding filehandles. Then you can use Perl’s built-in exists function on the hash to determine whether a given data type already has an associated filehandle. Here is how I would approach this task:

#! perl use strict; use warnings; my $in_file = 'input.txt'; my %out_files; open(my $in, '<', $in_file) or die "Cannot open file '$in_file' for reading: $!"; while (my $line = <$in>) { my ($datum, $type) = split ' ', $line; unless (exists $out_files{$type}) { my $filename = $in_file . $type . '.txt'; open(my $fh, '>>', $filename) or die "Cannot open file '$filename' for appending: $!"; $out_files{$type} = $fh; } print { $out_files{$type} } $datum . "\n"; } for (keys %out_files) { close $out_files{$_} or die "Cannot close the '$out_files{$_}' output file: $!"; } close $in or die "Cannot close file '$in_file': $!";

Update: Fixed die message for closing output files; also corrected fourth paragraph.

Hope that helps,

Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,


In reply to Re: filehandle in an array by Athanasius
in thread filehandle in an array by bestfa

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.