Category: Perl

  • Slurping and decoding JSON in Perl

    Lately been doing a bit with JSON as a config file. It is a convenient way to store config variables.

    Procedural/Imperative style (untested, needs error handling, etc):

    #!/usr/bin/perl
    use strict;
    use Path::Tiny qw (path);
    use Data::Dumper;
    use JSON;
    
    my $file = "config/myfile.json";
    my $DATA = decode_json path($file)->slurp_utf8;

    OOP if it floats your boat (untested, needs error handling, etc):

    #!/usr/bin/perl
    use strict;
    use Path::Tiny qw (path);
    use JSON;
    use Data::Dumper;
    
    my $file = "./config/myfile.json";
    my $json = new JSON;
    my $data = Path::Tiny->new($file)->slurp;
    
    print Dumper $json->decode($data);
    print Dumper $data;