将字符串转换为哈希值

时间:2018-05-23 12:23:49

标签: perl

有没有方法/ lib将字符串转换为哈希? 我有这样的字符串

{"hello"=>["world","perl"],"foo"=>"bar"}

我想访问不同的值,如果它是哈希

谢谢

3 个答案:

答案 0 :(得分:3)

将带有Perl数据结构的字符串转换为具有JSON数据结构的字符串,替换=>替换:并使用JSON包解码。

#!/usr/bin/env perl

use warnings FATAL => 'all';
use strict;
use Data::Dumper;
use JSON qw(decode_json); # use JSON::XS for more performance

my $string = '{"hello"=>["world","perl"],"foo"=>"bar"}';
$string =~ s/"=>/":/g;
print Dumper(decode_json($string));

<强>输出

$VAR1 = {
          'hello' => [
                       'world',
                       'perl'
                     ],
          'foo' => 'bar'
        };

答案 1 :(得分:2)

使用eval():

#!/usr/bin/env perl
use strict;
use Data::Dumper;

my $string = qw( {"hello"=>["world","perl"],"foo"=>"bar"} );
print "String: $string\n";

my $hash = eval($string);
print "Hash: ", Dumper($hash), "\n";

<强>输出

String: {"hello"=>["world","perl"],"foo"=>"bar"}
Hash: $VAR1 = {
          'foo' => 'bar',
          'hello' => [
                       'world',
                       'perl'
                     ]
        };

如果您对输入感到担忧,请使用reval()和Safe

#!/usr/bin/env perl
use strict;
use Safe;
use Data::Dumper;

my $string = qw( {"hello"=>["world","perl"],"foo"=>"bar"} );
print "String: $string\n";

my $compartment = new Safe;
my $hash = $compartment->reval($string);
print $@ ? "reval error: $@" : ("Hash: ", Dumper($hash)), "\n";

答案 2 :(得分:2)

如果你不介意我插入我自己的一个模块:Config::Perl使用PPI来解析这样的字符串,而不需要eval

use warnings;
use strict;
use Data::Dumper; # Debug
use Config::Perl;

my $str = q( {"hello"=>["world","perl"],"foo"=>"bar"} );

my $data = Config::Perl->new->parse_or_die(\$str)->{_}[0];

print Dumper($data); # Debug

输出:

$VAR1 = {
          'hello' => [
                       'world',
                       'perl'
                     ],
          'foo' => 'bar'
        };

(上面的代码假设您的数据中只有一个哈希引用,如果您有变化,那么您必须查看{{返回的]整个数据结构1}}。)