That can create empty files. Fix:

while there's a next line extract the ID check if ID matches the previous ID if not: set previous ID to current ID increment a counter if counter > 100 close current output file reset counter if output file isn't open open a new output file write the line to the current output file.

It can also create files with more than 100 records. Fix:

my $last_id; my @group; my $fh; my $line_counter = 0; my $file_counter = 0; sub output { if ($line_counter + @group > 100) { $fh = undef; $line_counter = 0; } if (!defined($fh)) { my $fn = sprintf('file%04d', $file_counter++); open($fh, '>', $fn) or die("Error create file $fn: $!\n"); } $line_counter += @group; print($fh splice(@group)); } while (<>) { my ($id) = /^(\S+)/; $last_id = $id if !defined($last_id); if ($id eq $last_id) { push @group, $_; } else { output(); } } output() if @group;

If there's more than 100 record for one id, it'll put them in the same file despite the limit.

Note that both my code and the parent's pseudocode assume that the records are grouped by id in the input file.


In reply to Re^2: Help spliting file into chunks by ikegami
in thread Help spliting file into chunks by mmittiga17

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.