Here's another answer:
use strict;
use warnings;
use 5.020;
use autodie;
use Data::Dumper;
my $infile = 'rand.txt';
my $outfile = 'newrand.txt';
{
local $/ = \(1024*1024);
open my $INFILE, '<', $infile;
open my $OUTFILE, '>', $outfile;
while(my $mb = <$INFILE>) {
while($mb =~ /(....)/g) {
my $int = oct("0b$1");
say $int;
print {$OUTFILE} $int if $int < 10;
}
}
close $OUTFILE;
close $INFILE;
}
Output:
$ perl -e 'print "1000" . "1101" . "0110" . "0100" . "1111" . "0101"' > rand.txt
$ cat rand.txt
100011010110010011110101
$ perl 1.pl
8
13
6
4
15
5
$ cat newrand.txt
8645
The script only traverses the file once, and there will only be 1 MB of the text in memory at any time.