简体   繁体   English

perl中十六进制值的总和

[英]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. 我正在尝试输入2个ascii文件并将它们输出到2个十六进制文件(sym.txt,sym2.txt)中,然后执行两个十六进制文件的总和,并将值的反转输出到最后一个文件(symout.txt)。我真的不明白我做错了什么......谢谢你提前帮忙: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 主要问题是你没有关闭$out$out1 ,所以打印到这些句柄的数据仍在内存中等待刷新

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 autodie以避免必须检查每个open调用的状态(您应该已经完成​​但没有!)

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";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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