我有一个我无法控制的函数,它返回一个实际上是哈希的字符串。它看起来像下面这样:
{"offset":0,"limit":500,"count":0,"virtual_machines":[]}
我需要检查计数是否大于0.因为输出是字符串而不是散列,我试图拆分字符串并从中获取输出。
相同的片段如下:
my $output = '{"offset":0,"limit":500,"count":0,"virtual_machines":[]}';
$output =~ s/ +/ /g;
my @words = split /[:,"\s\/]+/, $output;
print Dumper(@words);
这个输出是:
$VAR1 = '{';
$VAR2 = 'offset';
$VAR3 = '0';
$VAR4 = 'limit';
$VAR5 = '500';
$VAR6 = 'count';
$VAR7 = '0';
$VAR8 = 'virtual_machines';
$VAR9 = '[]}';
现在,我可以获得价值$ VAR7并获得计数。
有没有办法将字符串转换为哈希值,然后使用键来获取值而不是使用正则表达式和拆分。有人可以帮帮我吗?
答案 0 :(得分:5)
该字符串采用JSON格式。我只是做
<div class="parent">
<img id="mapImage" src="https://i.imgur.com/Y7HuHDQ.png" usemap="#image-map">
<map name="image-map">
<area target="" data-text="USA Shops: Manchester,TN - Num: 6621418372 WIXOM ,MI - Num:662728173" alt="USA" title="USA" href="" coords="110,140,182,141,186,148,198,146,198,140,214,139,224,134,234,143,221,150,213,154,205,156,205,170,199,174,194,181,193,188,162,182,158,171,149,173,145,179,141,170,124,168,121,173,112,168,105,158" shape="poly">
<area target="" data-text="Mexico Shops: Manchester,TN - Num: 6621418372 WIXOM ,MI - Num:662728173" alt="MEXICO" title="MEXICO" href="" coords="124,172,137,171,141,178,152,173,160,181,162,204,179,199,179,211,157,212,173,216,146,204,136,196,125,188" shape="poly">
<area target="" data-text="Japan Shops: Manchester,TN - Num: 6621418372 WIXOM ,MI - Num:662728173" alt="JAPAN" title="JAPAN" href="" coords="705,106,716,106,721,146,687,184,667,175" shape="poly">
<area target="" data-text="Germany Shops: Manchester,TN - Num: 6621418372 WIXOM ,MI - Num:662728173" alt="GERMANY" title="GERMANY" href="" coords="418,111,436,108,433,124,418,124" shape="poly">
<div class="tooltip" id="tooltip"></div>
</map>
</div>
答案 1 :(得分:-3)
如果所有冒号都只是分隔符,那么您可以用'=&gt;'替换它们并评估字符串。 但这可能不切实际。所以你可以使用JSON ...看起来字符串是JSON格式。尝试以下(为我工作: - ):
#!/usr/bin/perl
use JSON::Parse 'parse_json';
# the string is JSON
my $jstr = '{"offset":0,"limit":500,"count":0,"virtual_machines":[]}';
# oversimplified (not using json ... o.k. if no colons anywhere but as separators
my $sstr = $jstr;
$sstr =~ s/:/=>/g;
my $href = eval "$sstr";
printf("From oversimplified eval, limit == %d\n", $href->{limit});
# using JSON (looks like string is in JSON format).
# get JSON::Parse from CPAN (sudo cpan JSON::Parse)
my $jref = parse_json($jstr);
printf("From JSON::Parse, limit == %d\n", $jref->{limit});
1;
输出:
从过度简化的评估中,限制== 500
来自JSON :: Parse,limit == 500