YAML + File::Slurp = Beware!

ferreira on 2007-06-16T12:36:04

It is annoying to remember YAML.pm (as well as YAML::Syck) do not accept file handles as arguments to LoadFile (but only filenames). So to read a YAML from *DATA, I wrote a piece of code like this:

use File::Slurp qw( read_file );
use YAML qw( Load Dump );

my $etc = Load(read_file(\*DATA)); # <= that's what matters!!! print Dump($etc);

__DATA__ perl: url: rsync://public.activestate.com/perl-current/ home: base_path: /home/tmp target_dir: perl-current tarball: perl-current.tar.bz2 keep: 1


Only to find out it printed:

---
perl: ''


which definitely was not what I was looking for. The problem is that read_file is called in a list context and "perl:\n" is the only argument YAML::Load cares for. The fix:

my $etc = Load(scalar read_file(\*DATA));


The issue was a combination of File::Slurp trying to be handy and YAML not being helpful enough. It happens and calls for an improved API.


Decorators?

jordan on 2007-06-16T15:00:02

Does Perl need decorators to fix this kind of thing?

I'm not really clear on this in that I've never actually programmed in a language that supports decorators. Well, I've done Scheme and I'm assured that there is nothing that you cannot do in Scheme, but I've never done it.

I'm sure that Perl 6 has decorators as I'm as sure it has almost everything imaginable. I hear it has Traits and Roles and a lot of other things I've never even thought of. Unfortunately for me, it doesn't really have a stable existence that encourages me to use it for real-world solutions, but that's a small thing when compared to all these great features.

Re:Decorators?

chromatic on 2007-06-16T18:38:29

You can decorate instances of objects and classes at runtime with roles.

YAML::Syck 0.87 - No need for File::Slurp :-)

audreyt on 2007-06-16T16:54:21

[Changes for 0.87 (JSON::Syck 0.25) - 2007-06-17]

* New LoadFile and DumpFile functions for JSON::Syck.

* JSON::Syck now actually exports its functions if you ask for it.

* LoadFile and DumpFile now accept IO objects in addition to file names.
  Requested by: Adriano Ferreira
Thanks, applied!

Re:YAML::Syck 0.87 - No need for File::Slurp :-)

ferreira on 2007-06-16T17:25:49

Thank you, indeed. Remembering your motto (probably a little distorted by my bad memory): Less code is always better to write and maintain.

Re:YAML::Syck 0.87 - No need for File::Slurp :-)

audreyt on 2007-06-16T18:35:14

Well, that's a good motto, though the original was "Best coding = No coding".