skip to Main Content

The following code fails with an error saying that parse_json is undefined.

use strict;
use JSON::Parse;
my $x = "['a', 'b']";
my $json = parse_json($x);

But, this page claims it works: https://metacpan.org/pod/JSON::Parse

What am I doing wrong?

2

Answers


  1. The documentation repeatedly uses

    use JSON::Parse 'parse_json';
    

    and

    use JSON::Parse ':all';
    

    while you used

    use JSON::Parse;
    

    While all three load the module, only the former two exports parse_json.

    I believe it’s a good practice to list your imports even when you’re not required as it makes it a whole lot easier to work with code down the line. This is not relevant here because listing the imports is required.

    Login or Signup to reply.
  2. What @ikegami said, but here’s a little more info.

    Each module can decide how it "exports" symbols (variables or subs) to the loading namespace. And, since this is Perl, individual modules make different decisions about this. You know what they are doing by their documentation rather than what you have seen from another module.

    Some module export symbols without you asking if you don’t specify an import list:

    use File::Basename;  # you get dirname, basename, fileparse, fileparse_set_fstype
    

    Some modules require that you explicitly ask for symbols in your import list, and only export those:

    use File::Basename qw(basename);
    

    And you can ask to import nothing with an empty import list:

    use File::Basename ();
    my $name = File::Basename::basename($ARGV[0]);
    

    Some modules export only some symbols by default, while reserving some less commonly used symbols to be named explicitly in the import list:

    use File::Spec::Functions;  # catfile, and many others but not devnull
    
    use File::Spec::Functions qw(devnull);
    

    Once you specify an import list, you only get the symbols you explicitly list. You most list any symbol that was otherwise exported by default:

    use File::Spec::Functions qw(catfile devnull);
    

    Some modules specify group of symbols and "tag" them. These names typically start with a colon:

    use File::Spec::Functions qw(:ALL);  # all the functions
    
    use Socket qw(:addrinfo);
    use Socket qw(:addrinfo :crlf);
    

    One more thing

    Now, those are the modules that use the conventional exporter to do its work, and that’s what affects the original problem. There are other modules that use the import list to do other goofy things that don’t involve symbols. Since the "exporting" happens at compile time, some modules use the opportunity to configure themselves and do other tricks:

    use Getopt::Long qw(:config no_ignore_case bundling);
    

    And some modules use it to configure your calling code rather than themselves:

    use Mojo::Base qw(-strict -signatures);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search