justrajdeep
justrajdeep

Reputation: 903

Perl YAML::Load fails to load YAML dumped by YAML::Dump

I am facing this issue in YAML when using through perl. Can someone tell me where I am going wrong.

I have a code snippet

use YAML;
...
my $ifdef_struct = YAML::Load(<<'DS_TEMPLATE');
---
'<define_name>': undef
DS_TEMPLATE
my @tmp;
push(@tmp, $ifdef_struct);
$ifdef_struct = \@tmp; 
print YAML::Dump($ifdef_struct);    

This dumps out

    ---
    - '<define_name>': undef

Now when i change the code to have the same format as what is dumped by YAML::Dump

use YAML;
...
my $ifdef_struct = YAML::Load(<<'DS_TEMPLATE');
---
- '<define_name>': undef
DS_TEMPLATE
my @tmp;
push(@tmp, $ifdef_struct);
# $ifdef_struct = \@tmp;
print YAML::Dump($ifdef_struct);      

it is not able to load it and gives me the error

Uncaught exception from user code:
    YAML Error: Couldn't parse single line value
       Code: YAML_PARSE_ERR_SINGLE_LINE
       Line: 2
       Document: 1

Any suggestion are welcome.

Upvotes: 2

Views: 1042

Answers (1)

Chas. Owens
Chas. Owens

Reputation: 64909

The format YAML (the module) expects is:

---
-
    '<define_name>': undef

However,

---
- '<define_name>': undef

is valid YAML (the format). If you read the documentation for YAML, you will find the following warning:

If you want robust and fast YAML processing using the normal Dump/Load API, please consider switching to YAML::XS. It is by far the best Perl module for YAML at this time. It requires that you have a C compiler, since it is written in C.

YAML::XS has no problem with either version of the YAML:

#!/usr/bin/perl

use strict;
use YAML::XS;
use Data::Dumper;
use warnings;

my $one_line = YAML::XS::Load(<<'EOS');
---
- '<define_name>': undef
EOS

my $multi_line = YAML::XS::Load(<<'EOS');
---
-
   '<define_name>': undef
EOS

print Dumper($one_line, $multi_line);

Output:

$VAR1 = [
          {
            '<define_name>' => 'undef'
          }
        ];
$VAR2 = [
          {
            '<define_name>' => 'undef'
          }
        ];

Upvotes: 5

Related Questions