gpt4 book ai didi

perl - 为什么我的 perl 哈希没有返回值?

转载 作者:行者123 更新时间:2023-12-04 22:52:05 25 4
gpt4 key购买 nike

我正在摄取 CSV 文件:

"ID","LASTNAME","FIRSTNAME","PERM_ADDR1","PERM_ADDR2","PERM_CITY","PERM_ST","PERM_ZIP","DOB","LIB_TYPE","BARCODE","EMAIL","LOCAL_ADDR1","LOCAL_ADDR2","LOCAL_CITY","LOCAL_ST","LOCAL_ZIP","CAMPUS_ADDR1","CAMPUS_ADDR2","CAMPUS_CITY","CAMPUS_ST","CAMPUS_ZIP","DEPARTMENT","MAJOR"
"123","Lastname","Firstname","123 Home St","","Home City","HS","12345-6789","0101","S","1234567890","last.first@domain.local","123 Local St","","Local City","LS","98765-4321","123 Campus St","","Campus City","CS","54321-6789","IT",""

使用 Text::CSV,我试图将其解析为散列:

my $csv = Text::CSV->new();

chomp(my $line = <READ>);
$csv->column_names(split(/,/, $line));

until (eof(READ)) {
$line = $csv->getline_hr(*READ);
my %linein = %$line;
my %patron;

$patron{'patronid'} = $linein{'ID'};
$patron{'last'} = $linein{'LASTNAME'};
$patron{'first'} = $linein{'FIRSTNAME'};

print p(%linein)."\n";
print p(%patron)."\n";
}

使用这段代码,末尾的打印语句(使用Data::Printer)返回:

{
"BARCODE" 1234567890,
"CAMPUS_ADDR1" "123 Campus St",
"CAMPUS_ADDR2" "",
"CAMPUS_CITY" "Campus City",
"CAMPUS_ST" "CS",
"CAMPUS_ZIP" "54321-6789",
"DEPARTMENT" "IT",
"DOB" 0101,
"EMAIL" "last.first@domain.local",
"FIRSTNAME" "Firstname",
"ID" 123,
"LASTNAME" "Lastname",
"LIB_TYPE" "S",
"LOCAL_ADDR1" "123 Local St",
"LOCAL_ADDR2" "",
"LOCAL_CITY" "Local City",
"LOCAL_ST" "LS",
"LOCAL_ZIP" "98765-4321",
"MAJOR" "",
"PERM_ADDR1" "123 Home St",
"PERM_ADDR2" "",
"PERM_CITY" "Home City",
"PERM_ST" "HS",
"PERM_ZIP" "12345-6789"
}
{
first undef,
last undef,
patronid undef
}

我不明白的是为什么 %patron 没有被 %linein 的值填充。我想知道这是否与使用 Text::CSV 有某种关系,因为我在脚本的其他地方解析其他文件并且它们工作得很好。但是,这些文件不是 CSV 文件,而是固定宽度的文件,因此我手动解析它们。

最佳答案

尝试

 $csv->column_names(map {/"(.*)"/ and $1} split(/,/, $line))

代替

 $csv->column_names(split(/,/, $line));

您的 CSV key 被定义为文字字符串

 '"LASTNAME"' ,  '"FIRSTNAME"'

不仅仅是

 'LASTNAME' ,  'FIRSTNAME'

Data::Printer 在向您展示正在发生的事情方面做得还不错 -p(%linein) 中的所有键都显示为包含双引号作为字符串,而不是 p(%patron)

关于perl - 为什么我的 perl 哈希没有返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14612581/

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