Beefy Boxes and Bandwidth Generously Provided by pair Networks vroom
We don't bite newbies here... much
 
PerlMonks  

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)
gives
'$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)
gives
'--- - 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
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)];
    Data::Dumper->Dump(@arg2)
    
    gives
    
    '$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 dd.pl 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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2014-04-19 21:05 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    April first is:







    Results (483 votes), past polls