Perl - 将4个.txt文件转换为2个哈希值

时间:2014-02-27 16:24:22

标签: arrays perl hash

我正在尝试从4个文本文件中创建两个哈希值,每个文本文件都有匹配的行数,其中包含要与城市匹配的地址。

我希望这将是一个相当简单的,一切都在工作,除了我想在没有换行符的情况下将值存储在哈希值中,但是我在创建合并文本文件时尝试的其他每个选项都会读取地址和城市作为一个条目进入数组,而不是两个单独的。

此外,是否有一种简单的方法可以通过将值直接放入数组中来删除“NewCombo”和“OldCombo”文本文件?与以后散列的数组相同的东西,我还没有得到任何东西,但这工作,但我觉得我的代码是笨拙和过分的原样。虽然,我很高兴我唯一真正的问题是在我继续使用这个脚本之前摆脱换行符

#!/usr/bin/perl
use warnings;
use strict;

my $nafile = 'na.txt';
my $ncfile = 'nc.txt';
my $oafile = 'oa.txt';
my $ocfile = 'oc.txt';


open my $nafh, $nafile or die "Can't open New Address file!";
open my $ncfh, $ncfile or die "Can't open New City file!";
open my $oafh, $oafile or die "Can't open Old Address file!";
open my $ocfh, $ocfile or die "Can't open Old City file!";

open my $fh, '>', "NewCombo.txt" or die "Cannot open NewCombo.txt!";
while ( my $a = <$nafh>, my $b = <$ncfh> ) { 
    chomp( $a, $b );
    printf $fh qq|%s\n%s\n|, $a, $b; 
}
close $fh;

open my $fh2, '>', "OldCombo.txt" or die "Cannot open OldCombo.txt!";
while ( my $c = <$oafh>, my $d = <$ocfh> ) { 
    chomp( $c, $d );
    printf $fh2 qq|%s\n%s\n|, $c, $d; 
}
close $fh2;

my $OldFile = "OldCombo.txt";
open (FH, "< $OldFile") or die "Can't open OldFile for read!";
my @OldCombo;
while (<FH>) {
    push (@OldCombo, $_);
}
close FH or die "Cannot close OldFile!";

my $NewFile = "NewCombo.txt";
open (FH, "< $NewFile") or die "Can't open $NewFile for read: $!";
my @NewCombo;
while (<FH>) {
    push (@NewCombo, $_);
}
close FH or die "Cannot close NewFile!";

my %NewCombo = @NewCombo;
my %OldCombo = @OldCombo;

print %NewCombo;
print %OldCombo;

我认为在编程方面我很不错,并且了解MOST代码背后的逻辑。我对Perl仍然很陌生,感谢任何帮助

添加了详细信息 - 我尝试用逗号,制表符和空格分隔值,并在每个“设置”值之间/之后将它们的每个组合分开

1 个答案:

答案 0 :(得分:0)

似乎您的$/与文件中的行结尾不同。您可以为您阅读的任何行应用正则表达式s/[\r\n]//g