Sato
Sato

Reputation: 8602

How to convert 'hash string' to hash?

I have hash string stored in file, {"a"=>1,"b"=>2}, I open the file and store this hash string to $hash_string, How can I convert this $hash_string to $hash_string_ref = {"a"=>1,"b"=>2}?

Upvotes: 3

Views: 1488

Answers (3)

ikegami
ikegami

Reputation: 385764

Your data format appears to be "arbitrary Perl expression", which is a pretty awful data format. Why don't you use JSON or fuller-featured YAML instead?

use JSON::XS qw( encode_json decode_json );

sub save_struct {
   my ($qfn, $data) = @_;
   open(my $fh, '>:raw', $qfn)
      or die("Can't create JSON file \"$qfn\": $!\n");
   print($fh encode_json($data))
      or die("Can't write JSON to file \"$qfn\": $!\n");
   close($fh)
      or die("Can't write JSON to file \"$qfn\": $!\n");
}

sub load_struct {
   my ($qfn) = @_;
   open(my $fh, '>:raw', $qfn)
      or die("Can't create JSON file \"$qfn\": $!\n");
   my $json; { local $/; $json = <$fh>; }
   return decode_json($json);
}

my $data = {"a"=>1,"b"=>2};
save_struct('file.json', $data);

...

my $data = load_struct('file.json');

Upvotes: 5

FtLie
FtLie

Reputation: 773

use Perl Safe

The module will run any perl-code (in a sandbox) and return the result. Including decoding e.g. a structure dumped to a file.

code example:

use Safe;     
my $compartment = new Safe;
my $unsafe_code = '{"a"=>1,"b"=>2}';
my $result = $compartment->reval($unsafe_code);
print join(', ', %$result); 

Upvotes: 5

Simon Cozens
Simon Cozens

Reputation: 765

The simple answer:

$ echo '{"a"=>1,"b"=>2}' > val.pl
$ perl -le 'my $foo = do "val.pl"; print $foo->{a}'
1

The better answer: Consider using a better data serialization format, such as Storable or YAML, or even JSON.

Upvotes: 9

Related Questions