Paul
Paul

Reputation: 55

How to read perl data structures in external file using perl

I have a perl file containing some hash references (abc.pl) and i want to open this file in another perl file, so that i can convert it to json using Json XS. When i try to open abc.pl, perl reads it as text and i am unable to convert it into json.

So, i just wanted to know the way to read abc.pl in another perl file so that the hash references are read properly and then can be converted to json.

Upvotes: 3

Views: 1537

Answers (1)

friedo
friedo

Reputation: 66978

Assuming you have a data file that looks something like this:

$VAR1 = {
          'bar' => 2,
          'baz' => 3,
          'foo' => 1
        };

You can evaluate the structure using do function. For example,

use strict;
use warnings;

use JSON::XS;

my $data = do 'abc.pl';
my $json = encode_json $data;

print $json;

Upvotes: 4

Related Questions