2013-05-13 47 views
1

我正在處理一個Perl項目,其中有很多字符串包含引號中的ID和相應的值,以分號分隔。Perl - 引號中包含ID和相應值的進程字符串

例如:main_id「1234567」; second_id「My_ID」;名字「Andreas」;

每個ID名稱後面都有一個空格,每個分號後面都有空格。

有2個問題,我處理:

問題1:什麼是得到的值(不帶引號)發送到特定標識的最快方法?我第一次嘗試沒有成功:

$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」;名字「Andreas」;

哈希 「second_id」:

哈希{添加my_id} = {main_id => 1234567,second_id =>添加my_id,名稱=>安德烈亞斯}

我試了一下:

$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

解決方案不適合你嗎? – 2013-05-21 07:23:15

回答

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; 
1

Text::ParseWords模塊(標準的Perl分佈的一部分)使得這種simple.e。

#!/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; 
相關問題