3

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.

3
  • Hash references cannot exist in files. Please clarify. Do you mean it contains code that returns a hash reference? Commented May 29, 2012 at 23:40
  • the file contains combinations of data structures like these abc{z}={ a=>"bc", d=>"ef", g=>[h=>{t=>"ij"}]}; Commented May 30, 2012 at 0:07
  • I presume you mean $abc{z}, in which case it's Perl code. Make sure the file ends with \%abc, and you can use friedo's code. Commented May 30, 2012 at 1:12

1 Answer 1

4

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;
Sign up to request clarification or add additional context in comments.

4 Comments

thanx this worked for this example...but what if the file contains many complex data structures like this $VAR1{vr1} = { 'bar' => 2, 'baz' => 3, 'foo' => 1 }; $VAR1{vr2} = { 'bar' => 2, 'baz' => 3, 'foo' => 1 }; and so on
Then you'll probably want to split it somehow and use eval on the resulting strings.
splitting and using eval evaluates them as strings and doesnt convert it into json
eval will evaluate them. It's up to you to convert it to JSON once you have deserialized the reference. I've already shown you how to do that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.