我正在开发一个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的哈希的最快方法是什么,如下所示:
String:main_id“1234567”; second_id“My_ID”;名字叫“安德烈亚斯”;
“second_id”的哈希:
hash {My_ID} = {main_id => 1234567,second_id => My_ID,name =>安德烈亚斯}
我尝试了什么:
$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;
这很有效,但是有更快/更好的解决方案吗?
答案 0 :(得分: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;
答案 1 :(得分: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;