简体   繁体   中英

Sum of hex values in perl

I am trying to input 2 ascii files and output them into 2 hex files (sym.txt ,sym2.txt) and then do the sum of two hex files and output the reverse of the value into a last file (symout.txt).I really don't see what I'm doing wrong ... Thank you for the help in advance :D.

use strict;
use warnings 'all';

open my $in, "<", "f1.txt";
my $input = do { local $/; <$in> };

open my $out, ">", "sym.txt";
print $out unpack 'H*', $input;

open my $in1, "<", "f2.txt";
my $input1 = do { local $/; <$in1> };

open my $out1, ">", "sym2.txt";
print $out1 unpack 'H*', $input1;

    open(my $fh1, '<', 'sym.txt') or die $!;
    open(my $fh2, '<', 'sym2.txt') or die $!;
    open my $fh_out, '>', 'symout.txt' or die $!;

   until ( eof $fh1 or eof $fh2 ) {

    my @l1 = map hex, split '', <$fh1>;
    my @l2 = map hex, split '', <$fh2>;

    my $n = @l2 > @l1 ? @l2 : @l1;

    my @sum = map {
        no warnings 'uninitialized';
        $l1[$_] + $l2[$_];
    } 0 .. $n-1;

    @sum = map { sprintf '%X', $_ } @sum;

        print { $fh_out } reverse(@sum), "\n";
}

The main problem is that you haven't closed $out or $out1 , so the data that has been printed to those handles is still in memory waiting to be flushed

It's best to use lexical file handles (as you are doing) and add blocks so that the handles are closed implicitly when they go out of scope

Here's an example of what I mean. Note that I've also added use autodie to avoid having to check the status of every open call (which you should have done but didn't!)

use strict;
use warnings 'all';
use v5.14;
use autodie;

{
    my $input = do {
        open my $in, '<', 'f1.txt';
        local $/;
        <$in>
    };

    open my $out, '>', 'sym.txt';
    print $out unpack 'H*', $input;
}

{
    my $input = do {
        open my $in, '<', 'f2.txt';
        local $/;
        <$in>
    };

    open my $out, '>', 'sym2.txt';
    print $out unpack 'H*', $input;
}

open my $fh1, '<', 'sym.txt';
open my $fh2, '<', 'sym2.txt';

until ( eof $fh1 or eof $fh2 ) {

    my @l1 = map hex, split //, <$fh1>;
    my @l2 = map hex, split //, <$fh2>;

    my $n = @l2 > @l1 ? @l2 : @l1;

    my @sum = map {
        no warnings 'uninitialized';
        $l1[$_] + $l2[$_];
    } 0 .. $n-1;

    @sum = map { sprintf '%X', $_ } @sum;

    open my $out, '>', 'symout.txt';
    print { $out } reverse(@sum), "\n";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM