Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Serialization and eval in YAML

by throop (Chaplain)
on Aug 13, 2012 at 16:30 UTC ( #987152=perlquestion: print w/ replies, xml ) Need Help??
throop has asked for the wisdom of the Perl Monks concerning the following question:

Do I need to use eval when reading in a YAML file?

I'm used to serializing with Data::Dumper. It produces a dump string which, when loaded, sets variables to values. E.g:

use Data::Dumper; @arg2 = [{a => 1, b =>2}], [qw($balloon)]; Data::Dumper->Dump(@arg2)
'$balloon = { \'a\' => 1, \'b\' => 2 };
When that's printed to a file, and later loaded, $balloon gets set right. But for YAML:
use YAML::XS; @arg2 = ([{a => 1, b =>2}], [qw($balloon)]); Dump(@arg2)
'--- - a: 1 b: 2 --- - $balloon '
which, when loaded, gives,
0 ARRAY(0x89889e8) 0 HASH(0x8994130) 'a' => 1 'b' => 2 1 ARRAY(0x8ef27c8) 0 '$balloon'
Should I just use eval to get $balloon set to the right value? Or is there a YAML function to do this?

Comment on Serialization and eval in YAML
Select or Download Code
Replies are listed 'Best First'.
Re: Serialization and eval in YAML
by Anonymous Monk on Aug 13, 2012 at 17:15 UTC

    The YAML interface is nothing like Data::Dumper, use this instead

    my $string = Dump $oldbaloon; my $baloon = Load $string;

    Or the corresponding DumpFile/LoadFile

Re: Serialization and eval in YAML
by thundergnat (Deacon) on Aug 13, 2012 at 18:15 UTC
    use Data::Dumper;
    @arg2 = [{a => 1, b =>2}], [qw($balloon)];
    '$balloon = {
                 \'a\' => 1,
                 \'b\' => 2

    Really? Using no version of Perl that I've ever used.

    use warnings; use Data::Dumper; @arg2 = [{a => 1, b =>2}], [qw($balloon)]; print Data::Dumper->Dump(@arg2)
    Useless use of anonymous list ([]) in void context at line 3.
    $VAR1 = [
                'a' => 1,
                'b' => 2

    Precedence problem. You need parenthesis around the array. And lose the sigil on $balloon.

    Update: removed some unnecessarily snarky commentary.

      use Data::Dumper; print Data::Dumper->Dump( [{a => 1, b =>2}], [qw($balloon)] ); __END__ $balloon = { 'a' => 1, 'b' => 2 };

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://987152]
Approved by lidden
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (11)
As of 2015-11-27 09:22 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (722 votes), past polls