in reply to Split a binary file in pieces

#!/usr/bin/perl $/ = \10_000_000; # according to IEEE, otherwise \10_485_760 open my $in, "<", $ARGV[0] or die $!; binmode $in; my $n = 1; while (<$in>) { open my $out, ">", "outfile_".$n++ or die $!; binmode $out; print $out $_; }

Update: changed <> to a manually opened <$in>, because I couldn't find a sensible way to binmode ARGV...  Does anyone know how to do it?

Update-2:  use open IN => ':raw'; does seem to work for <>.  Or something ugly as

while (<>) { binmode(ARGV), seek(ARGV,0,0), next if $.==1; ...

Replies are listed 'Best First'.
Re^2: Split a binary file in pieces
by ZJ.Mike.2009 (Scribe) on Mar 10, 2010 at 04:44 UTC
    I'm learning Perl. Thanks for the code. But how do we join the split pieces together? Thanks :)
      Write out how you would do it in words, then translate words into code

        You're right :) I'm thinking sometimes because the Perl community is too kind and helpful, I'm just tempted to become very very lazy :)

        Anyway I tried translating words into code and came up with the following ugly code, which seems to be working. But I know it's ugly :)

        use strict; use warnings; $/ = \20_000_000; #I've just split a 20-meg file open my $f1, "<", '1' or die $!; # piece 1 is named 1 binmode $f1; open my $f2, "<", '2' or die $!; # piece 2 is named 2 binmode $f2; while(my $x = <$f1>){ while(my $y = <$f2>){ open my $out, ">", "outfile" or die $!; binmode $out; print $out $x.$y; } }

        UPDATE: tried optimizing a few lines. It looks a little cleaner

        use strict; use warnings; $/ = \20_000_000; #I've just split a 20-meg file into 2 pieces open my $f1, "<", '1' or die $!; piece 1 is named 1 binmode $f1; open my $f2, "<", '2' or die $!; # piece 2 is named 2 binmode $f2; while(defined(my $x = <$f1>) && (my $y = <$f2>)){ open my $out, ">", "outfile" or die $!; binmode $out; print $out $x.$y; }