Search code examples
perlyaml

Read YAML from a variable to hash


I have a linux command which fetches some data in YAML format from an API. I was looking for a way to populate this variable to a hash array. I was trying YAML::Tiny, and the chunk of code that I wrote was:

    use YAML::Tiny;
    my $stuff = `unix command that returns as yaml output`
    my $yaml = YAML::Tiny->new;
    $yaml = YAML::Tiny->new->read_string->($stuff);

But, running with this code will error out as:

    Can't use string ("") as a subroutine ref while "strict refs" in use

$stuff variable would look like:

    Cluster1:
        source_mount: /mnt/uploads
        dir: /a /b
        default: yes
        destination_mount: /var/pub

    Cluster2:
        source_mount: /mnt/uploads
        dir: /c /d /e
        default: no
        destination_mount: /var/pub

Solution

  • You should not use new twice, and there should not be -> after read_string (refer to the POD for YAML::Tiny). Change:

    $yaml = YAML::Tiny->new->read_string->($stuff);
    

    to:

    $yaml = YAML::Tiny->read_string($stuff);
    

    Here is a complete working example:

    use warnings;
    use strict;
    use YAML::Tiny;
    
    my $stuff = '
        Cluster1:
            source_mount: /mnt/uploads
            dir: /a /b
            default: yes
            destination_mount: /var/pub
    
        Cluster2:
            source_mount: /mnt/uploads
            dir: /c /d /e
            default: no
            destination_mount: /var/pub
    ';
    my $yaml = YAML::Tiny->new();
    $yaml = YAML::Tiny->read_string($stuff);
    print $yaml->[0]->{Cluster2}->{dir}, "\n";
    

    Output:

    /c /d /e