http://www.perlmonks.org?node_id=620076

I recently discovered YAML and thought it was very cool, so I've been anxiously awaiting a chance to actually use it. Well, I just started a new project and I thought YAML would be perfect for loading the config file.

I immediately had problems, because the YAML parser was unable to read in my config file. It gave me an error saying 'stream does not end with newline' - which left me perplexed because the file did, indeed, have a newline!

Since the problem seemed to be with the YAML syntax, I thought it would be clever to make Perl generate the file for me. I hardcoded a data structure in Perl and wrote out YAML using the Dump() command:

# yam1.pl use strict; use warnings; use YAML; my $config = { NAME => 'John Doe', ADDRESS => '123 Main St.', PHONE => { 'Home' => '123-4444', 'Work' => '123-5555', }, CONTACTS => [ 'John', 'Paul', 'George', ], }; print Dump( $config ), "\n";

I saved the output as config.yml, which looks like this:

--- ADDRESS: 123 Main St. CONTACTS: - John - Paul - George NAME: John Doe PHONE: Home: 123-4444 Work: 123-5555

This looked pretty much like what I already had, and sure enough, when I tried reading it back in, I again got the same error as before. This is what my reader script looked like:

# yam2.pl -- does NOT work! use strict; use warnings; use YAML; use Data::Dumper; # load YAML file into perl hash ref? my $config = Load("config.yml"); print Dumper($config), "\n";

I am too ashamed to admit on this board how long it took me to figure out the problem here, but I DID read the docs on cpan, search on google, search here, and search on the official yaml site, to no avail.

Here's the solution - which I'm posting here on the off chance that someone, some where, some day, may have the same bad fortune that I did, and will find this helpful.

# yam3.pl - Works! Yippie! use strict; use warnings; use YAML; use Data::Dumper; # step 1: open file open my $fh, '<', 'config.yml' or die "can't open config file: $!"; # step 2: slurp file contents my $yml = do { local $/; <$fh> }; # step 3: convert YAML 'stream' to perl hash ref my $config = Load($yml); print Dumper($config), "\n";

And there you have it: the Load function does not load a FILE, it loads a STREAM. Okay - so now I feel like an idiot. But I went back and read the documentation again, and this really is not that obvious. An example would have helped a bunch. There wasn't one there, but now there's one here.

Update:

After going back and very carefully reading the docs a third time (after bossman's replay) I finally found what I was really looking for all along - the LoadFile function:

# yam4.pl - Works also! Yippie! use strict; use warnings; use YAML; use Data::Dumper; # step 1: open file open my $fh, '<', 'config.yml' or die "can't open config file: $!"; # step 2: convert YAML file to perl hash ref my $config = LoadFile($fh); print Dumper($config), "\n";

'You're Welcome' in advance...