tags:

views:

145

answers:

3

I need to create a YAML file to store some configuration data for a Perl script. This seems like it should be really easy but I haven't been able to work it out, I think if I had just one simple example to copy I'd be fine. I want to do something like this:

-----test.yaml-----
image_width: 500
show_values: 0
-------------------

------test.perl------
use YAML;

my (%settings) = Load('test.yaml');
print "The image width is", $settings{image_width};
---------------------
+4  A: 

Try dumping out the configuration you want.

use strict;
use warnings;

use YAML;

my %settings = (
        foo => 1,
        bar => [qw/one two three/],
);

print Dump(\%settings);

This prints

---
bar:
  - one
  - two
  - three
foo: 1

Also, wikipedia has a good overview of YAML if the specification is a bit too dense.

szbalint
+1; I do this from the command line all the time: `perl -MYAML::Any -wle'my $data = { some data here }; print Dump($data)'` It's also a good idea to unyamlize any config file you make and call Data::Dumper against it, to verify that you made the changes you intended to.
Ether
I do the same thing. It's a lot easier for me to get the initial file correct this way than it is if I start from scratch.
Greg
While this is a good way to create a YAML config file, it doesn't address the problem he has with his code. His YAML is actually usable; it's the code that doesn't work.
cjm
+3  A: 

Try this:

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

use YAML qw(LoadFile);

my $settings = LoadFile('test.yaml');
say "The image width is ", $settings->{image_width};

– Michael

mscha
Thanks! That's perfect.
+3  A: 

Your fundamental problem here is that Load expects a string containing YAML, not a filename. You wanted LoadFile instead (which is not exported by default). Also, you should use YAML::XS instead of YAML if you can, as it's a better implementation. (But YAML should be adequate for a simple config file.)

The other problem is that LoadFile will return a hash reference (well, if your YAML looks like a hash, as yours does), not a list you can use to initialize a hash.

Try this:

use strict;
use warnings;
use YAML::XS qw(LoadFile);

my $settings = LoadFile('test.yaml');

print "The image width is ", $settings->{image_width};

(You can delete the ::XS if you don't want to (or can't) install YAML::XS. The program will work with no other changes.)

cjm
For config files I prefer YAML::Tiny.
Michael Carman