与许多人在他们的答案中所说的相反,您不需要前瞻(除了 Regex 自己的),您只需要捕获部分分隔符,如下所示:
my @hash_fields = grep { length; } split /\s*(\w+):\s*/;
我的完整解决方案如下:
my %handlers
= ( players => sub { return [ grep { length; } split /\s*,\s*/, shift ]; }
, personnel => sub {
my $value = shift;
my %personnel;
# Using recursive regex for nested parens
while ( $value =~ m/([^(]*)([(](?:[^()]+|(?2))*[)])/g ) {
my ( $name, $role ) = ( $1, $2 );
$role =~ s/^\s*[(]\s*//;
$role =~ s/\s*[)]\s*$//;
$name =~ s/^\s+//;
$name =~ s/\s+$//;
$personnel{ $role } = $name;
}
return \%personnel;
}
);
my %hash = grep { length; } split /(?:^|\s+)(\w+):\s+/, <DATA>;
foreach my $field ( keys %handlers ) {
$hash{ $field } = $handlers{ $field }->( $hash{ $field } );
}
转储看起来像这样:
%hash: {
personnel => {
'assistant coach (es)' => 'Aitor Karanka',
'head coach' => 'José Mourinho'
},
players => [
'Zinédine Zidane',
'Ronaldo',
'Luís Figo',
'Roberto Carlos',
'Raúl'
],
stadium => 'Santiago Bernabeu',
team => 'Real Madrid',
title => 'Football'
}