Simple example of using data from a YAML configuration file in a Perl script

后端 未结 3 877
甜味超标
甜味超标 2021-02-06 00:46

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 h

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-06 01:43

    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.)

提交回复
热议问题