3

I have text file looks like that:

float a[10] = {
    7.100000e+000 ,
    9.100000e+000 ,
    2.100000e+000 ,
    1.100000e+000 ,
    8.200000e+000 ,
    7.220000e+000 ,
    7.220000e+000 ,
    7.222000e+000 ,
    1.120000e+000 ,
    1.987600e+000
};

unsigned int col_ind[10] = {
    1 ,
    4 ,
    3 ,
    4 ,
    5 ,
    2 ,
    3 ,
    4 ,
    1 ,
    5
};

Now, I want to convert each array (float / unsigned int) to different binary files - big endian type, a binary file for all float values and a binary file for all integer values.

What is the simple way to do it in Perl, consider I have over two millon elements in each array?

1 Answer 1

3

You'll want to look into binmode and pack. Here's an example that might get you started. I'm not sure I've chosen the pack templates that you need, but see the pack documentation for all of the choices.

use strict;
use warnings;

my ($fh, $pack_template);

while (my $line = <>){
    if ( $line =~ /(float|int)/ ){
        $pack_template = $1 eq 'int' ? 'i' : 'f';

        undef $fh;
        open $fh, '>', "$1.dat" or die $!;
        binmode $fh;

        next;
    }

    next unless $line =~ /\d/;
    $line =~ s/[,\s]+$//;

    print $fh pack($pack_template, $line);
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.