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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|