Skip to content

Instantly share code, notes, and snippets.

@7stud
Created February 10, 2018 01:44
Show Gist options
  • Save 7stud/c976029ce76370528f39f1059f6e6c8a to your computer and use it in GitHub Desktop.
Save 7stud/c976029ce76370528f39f1059f6e6c8a to your computer and use it in GitHub Desktop.
Convert ones and zeros

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment