gpt4 book ai didi

perl - 如何将 2 个文件与 4 列组合成 perl 中的哈希

转载 作者:行者123 更新时间:2023-12-04 02:56:06 25 4
gpt4 key购买 nike

我正在尝试将一个包含 4 列和多行的文件加载到哈希中,我需要通过包含字母数字数据并与日期匹配的第一个字段将其与另一个文件组合这是我的数据示例:

file 1:
AOKX 495408, L, 04/02/13, SWCOMP
AOKX 495408, L, 04/20/13, SWCOMP
BLHX 102, L, 04/01/13, WILDCOM
CRDX 7067, L, 04/05/13, TYCO
WW 9030, L, 04/02/13, HALLI

file2:
AOKX 495408, L, 04/15/13, SWCOMP
BLHX 102, L, 04/03/13, WILDCOM
CRDX 7067, L, 04/20/13, TYCO
WW 9030, L, 04/30/13, HALLI
BLHX 102, L, 04/30/13, WILDCOM

output file needs to look like:
AOKX 495408 L 04/02/13 04/15/13 SWCOMP
BLHX 102 L 04/02/13 04/03/13 WILDCOM (more than 1 date exists 04/30/13)

这是我目前所拥有的 - 它完全不起作用 - 当测试并想要打印 $key 中的内容时,它给了我第二个字段。我似乎无法让它与 2 个以上的字段一起使用。所以我被困在这里。

my %hash;

open FILE1, "<", "out1.txt" or die "$!\n";

while ( <FILE1> ) {
chomp $_;
my ( $key, $le, $date, $company ) = split ',', $_;
$hash{$key} = $le, $date, $company;
push @{ $hash{$key} }, $_;
}

close FILE1;

非常感谢,我将格式更改为 [$le, $date, $company]。我的下一个问题是,一旦将两个文件读入哈希,我无法弄清楚如何将它们组合起来。我需要能够将第一个字段(车号)与两个文件中的日期相匹配。要么我的文件有多个日期列表。如果不存在日期,它仍会被写出。如果有多个日期,我真的需要将最接近的日期彼此匹配。 (例如 04/01/2013 04/05/2013 然后 04/06/2013 04/30/2013)我希望这是有道理的。

所以这是我到目前为止所拥有的(非常基本只是想弄清楚每一步)非常感谢任何帮助,因为我只是在学习并且真的需要完成这项工作......谢谢

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

my $cnt = 0;
open FILE1, "<", "out1.txt" or die "$!\n";

my %hash;

while ( <FILE1> ) {
chomp $_;
my ( $key, $le, $date, $company ) = split ',', $_;
$hash{$key} = [$le, $date, $company];
push @{ $hash{$key} }, $_;
$cnt++;
# print "$key $date\n";
}

print "total pcon records processed: $cnt\n"; #just to verify all records read
$cnt=0;

close FILE1;

open FILE2, "<", "out2.txt" or die "$!\n";
open OUTFILE, ">", "final.txt" or die "$!\n";

while (<FILE2>) {
my ( $rkey, $rle, $rdate, $rcompany ) = split ',', $_;
$hash{$rkey} = [$rle, $rdate, $rcompany];
push @{ $hash{$rkey} }, $_;
$cnt++;
# print OUTFILE "\n"; #to write out once figure out how to combine

}
print "total rcpl records processed: $cnt\n"; #just to verify all records read

close FILE2;
close OUTFILE;

需要输出看起来像:

 AOKX 495408 L  04/02/13 04/15/2013 SWCOMP 
AOKX 495408 L 04/20/13 SWCOMP
BLHX 102 L 04/01/13 04/03/2013 WILDCOM
BLHX 102 L 04/30/2013 WILDCOM

最佳答案

当 perl 看到该行时

$hash{$key} = $le, $date, $company;

它将此解释为从列表 ($le, $date, $company) 到列表 ($hash{$key}) 的列表赋值从第一个列表中的每个项目到第二个列表中的匹配项目,并丢弃没有匹配项目的任何项目。您要做的是像这样将包含值的数组引用分配给散列键

$hash{$key} = [$le, $date, $company];

关于perl - 如何将 2 个文件与 4 列组合成 perl 中的哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16678991/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com