我的这个字符串包含用户数据:
"1111|John|Smith|32\n2222|Sam|Adams|25\n3333|Chris|Stevens|30\n"
我试图用正则表达式读取它并创建这样的哈希(使用JSON表示法使其易于理解):
{
"1111": {
"IdNumber" : "1111",
"Name" : "John",
"LastName" : "Smith",
"Age" : "32"
},
"2222": {
"IdNumber" : "2222",
"Name" : "Sam",
"LastName" : "Adams",
"Age" : "25"
},
"3333": {
"IdNumber" : "3333",
"Name" : "Chris",
"LastName" : "Stevens",
"Age" : "30"
},
}
父哈希必须有用户' id作为键,值将是包含所有用户数据的子哈希。
我尝试使用命名组直接协助生成的$+
哈希:
use strict;
use warnings;
use Data::Dumper;
my $str = "1111|John|Smith|32\n2222|Sam|Adams|25\n3333|Chris|Stevens|30\n";
my %users;
while ($str =~ /(?<IdNumber>.*?)\|(?<Name>.*?)\|(?<LastName>.*?)\|(?<Age>.*?)/g){
$users{$+{IdNumber}} = %+;
}
print Dumper %users;
但我得到了这个结果:
$VAR1 = '1111';
$VAR2 = 4;
$VAR3 = '3333';
$VAR4 = 4;
$VAR5 = '2222';
$VAR6 = 4;
在我看来,子哈希正在转换为标量,但我无法找到错误。
你知道吗?谢谢。答案 0 :(得分:4)
open(my $fh, '<', \$str);
my %users;
while (<$fh>) {
chomp;
my %row;
@row{qw( IdNumber Name LastName Age )} = split /\|/;
$users{ $row{IdNumber} } = \%row;
}
或者,
my %users;
for (split /^/m, $str) {
chomp;
my %row;
@row{qw( IdNumber Name LastName Age )} = split /\|/;
$users{ $row{IdNumber} } = \%row;
}
或者,因为我们可以安全地忽略训练空白行,
my %users;
for (split /\n/, $str) {
my %row;
@row{qw( IdNumber Name LastName Age )} = split /\|/;
$users{ $row{IdNumber} } = \%row;
}