We could adjust the answer given by mr_mischief by pulling the if block out of the inner foreach and using the whole file's size instead of calculating a remainder.

#!/usr/bin/perl use strict; use warnings; my $parts = shift; ### how many parts to split my @file = @ARGV; ### the files to split foreach ( @file ) { ### how big should the new file be? my $size = (-s) / $parts; ### open the input file open my $in_fh, $_ or warn "Cannot read $_: $!"; binmode $in_fh; ### for all but the last part, read ### the amount of data, then write it to ### the appropriate output file. for my $part (1 .. $parts - 1) { ### read an output file worth of data read $in_fh, my $buffer, $size or warn "Read zero bytes from $ +_: $!"; ### write the output file open my $fh, "> $_$part" or warn "Cannot write to $_$part: $!" +; print $fh $buffer; } # for the last part, read the rest of # the file. Buffer will shrink # to the actual bytes read. read $in_fh, my $buffer, -s or warn "Read zero bytes from $_: $!"; open my $fh, "> $_$parts" or warn "Cannot write to $_$parts: $!"; print $fh $buffer; } __END__

The same weeknesses exist for memory usage. There could be better checks for file existence, too.


In reply to Re: How do i split a file into given number of parts. by CharlesClarkson
in thread How do i split a file into given number of parts. by turumkhan

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.