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}
?
Add a comment
|
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.
-
1+1 for the serialization advice. But the
do
thing is not the most safe option. – simbabque Feb 27 '13 at 9:41 -
do
in this case, has all of the same security problems of stringeval
. – Brad Gilbert Feb 27 '13 at 17:08
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);
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');
-
The "arbitrary Perl expression" is std dump/dumper for Perl, and if you know that the receiver will be Perl as well, this data format is often a good solution. But of course, if you may expect other receivers of the data than Perl, decoders for JSON/YAML, or even xml is far more common. – FtLie Feb 27 '13 at 20:01
-
-
@FtLie, And then there's the claims that a format that's hard to read and has no parser is a good format. DD is meant as a debugging tool, and it's not even particularly good at that. – ikegami Feb 27 '13 at 21:31
-
-
I am sorry but you got three wrongs on a row. 1) Data::Dump would produce a result quite close, and the question contains a simplified example (Dumper would include a $VAR= in front). 2) I claimed that Perl is easy to read for Perl, and Perl do parse Perl quite well, not that a Perl data::Dump(er) is good for everything. 3) which error you you get? It works fine for me. Finally, please contribute to answering the question (how to parse a given string). Btw Using Dumper/Safe is the most common serializer in e.g. CGI::Session. – FtLie Feb 28 '13 at 9:44