The best/easiest solution would depend on how many distinct values are possible in the first column of the file, which determines how many output files you're going to create.

If there are fewer than a couple dozen, then you can just open that many output files and print each line to one of those files as you read through the input.

If there are lots of different values/output files, then it would be better to sort the input file first, so that distinct values in the first column are clumped together, and you can open and close output files as you go through the input, and you only need one output file open at any given time.

Since the latter approach works equally well for all cases, that's the one I'd rather go with. It assumes that you have a decent utility to sort the input before feeding it to your perl script (e.g. unix/GNU "sort"):

use strict; use warnings; open( INPUT, "sort $ARGV[0] |" ) or die "can't sort $ARGV[0]: $!"; my $outname = ""; while (<INPUT>) { if ( /^(.+?),/ ) { my $newname = $1; if ( $newname ne $outname ) { close OUT if ( $outname ); open( OUT, ">$newname" ) or die "can't output to $newname: +$!"; $outname = $newname; } print OUT; } else { warn "Sorted input from $ARGV[0] had unusable data at line $.: + $_\n" } } close OUT;
(not tested; updated to remove the unnecessary $col variable, and to use ".+" instead of ".*" in the regex match to capture the first-column/file-name string -- don't want an empty string there.)

In reply to Re: Split up file depending unique values 1st column by graff
in thread Split up file depending unique values 1st column by GertMT

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.