Hello, here is a little function (split_file) which split a file into a given number of part. This is quite simple code, but ease the dispatching of a list of reference to be handled by several jobs running in parallel.

Of course, I am not a Perl expert, and any advise on doing it in a fancier or more efficient way is welcome

The function is called with two arguments, the name of the file, and the number of files to create. The countLines subroutine is called to count the number of lines in a file.

Of course, I am quite new to perlmonks, so If you find that this has nothing to do here, just tell me.

Updates:

sub countLines { my $filename=shift(@_); die("amaUtils:countLines:invalid filename") if(length($filename)== +0); open(TMP,"<$filename") or die("amaUtils:countLines unable to open +file $filename"); my $nb=0; $nb += tr/\n/\n/ while sysread(TMP, $_, 2 ** 16); close TMP; return $nb; } sub split_file { my $filename=shift(@_); my $nbFiles=shift(@_); die("amaUtils:split_files invalid number") if($nbFiles !~ /^\d+$/) +; die("amaUtils:split_files invalid number") if($nbFiles < 1); my $curNb=1; my $totalCount=countLines($filename); my $nbLinesPerFile=int($totalCount/$nbFiles); $nbLinesPerFile++ if( ($nbLinesPerFile * $nbFiles)!=$totalCount); my $currentCount=0; open(ORIG,"<$filename"); my ($newfile,$ext)=split(/\./,$filename); open(DEST,">${newfile}_".sprintf("%02d",${curNb}).".$ext"); while(<ORIG>) { if($currentCount==$nbLinesPerFile) { close DEST; $curNb++; $currentCount=0; open(DEST,">${newfile}_".sprintf("%02d",${curNb}).".$ext") +; } print DEST $_; $currentCount++; } close DEST; close ORIG; }

In reply to split file in N part by jeepj

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.