1

我正在开发一个 Perl 项目,其中有很多字符串,其中包含 id 和引号中的相应值,用分号分隔。

示例:main_id "1234567"; second_id "My_ID"; 名称“安德烈亚斯”;

每个 ID 名称后面和每个分号后面都有一个空格。

我正在处理两个问题:

问题1:获取特定id的值(不带引号)的最快方法是什么?我的第一次尝试没有奏效:

$id_list = 'main_id "1234567"; second_id "My_ID"; name "Andreas";';
$wanted_id = 'second_id';
($value = $id_list) =~ s/.*$wanted_id\w"([^"])";.*/$1/;

问题 2:将这个字符串 id 转换为特定 id 的哈希的最快方法是什么,如下所示:

字符串:main_id“1234567”;second_id "My_ID"; 名称“安德烈亚斯”;

“second_id”的哈希:

hash{My_ID} = {main_id => 1234567, second_id => My_ID, name => Andreas}

我尝试了什么:

$id_list = 'main_id "1234567"; second_id "My_ID"; name "Andreas";';
$wanted_id = 'second_id';
%final_id_hash;
%hash;
my @ids = split ";", $id_list;
foreach my $id (@ids) {
   my ($a,$b)= split " ", $id;
    $b =~ s/"//g;
    $hash{$a} = $b;
}    
$final_hash{$hash{$wanted_id}}= \%hash;

这行得通,但是有更快/更好的解决方案吗?

4

2 回答 2

1

Text::ParseWords模块(标准 Perl 发行版的一部分)使这变得简单。

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

use Text::ParseWords;
use Data::Dumper;

my %final_hash;
my $wanted_id = 'second_id';
my $id_list = 'main_id "1234567"; second_id "My_ID"; name "Andreas";';

my @words = parse_line '[\s;]+', 0, $id_list;
pop @words; # Lose the extra field generated by the ; at the end
my %hash = @words;

$final_hash{$hash{$wanted_id}} = \%hash;

say Dumper \%final_hash;
于 2013-05-13T16:08:00.277 回答
0

问题1,

my %hash = map {
  map { s/ ^" | "$ //xg; $_ } split /\s+/, $_, 2;
}
split /;\s+/, qq{main_id "1234567"; second_id "My_ID"; name "Andreas"};

use Data::Dumper; print Dumper \%hash;
于 2013-05-13T15:25:44.060 回答