1

Here is my code that I try to open the file to get data and change it to UTF-8, then read each line and store it in variable my $abstract_text and send it back in JSON structure.

my $fh;
if (!open($fh, '<:encoding(UTF-8)',$path))
    {
    returnApplicationError("Cannot read abstract file: $path ($!)\nERRORCODE|111|\n");
    }
printJsonHeader;
my @lines = <$fh>;
my $abstract_text = '';
foreach my $line (@lines)
    {
    $abstract_text .= $line;
    }

my $json = encode_json($abstract_text);
close $fh;
print $json;

By using that code, I get this error;

hash- or arrayref expected (not a simple scalar, use allow_nonref to allow this)

error message also point out that the problem is in this line; my $json = encode_json($abstract_text);

I want to send the data back as a string (which is in UTF-8). Please help.

2
  • @Zaid Your close vote is unwarranted: this one is not about usage per se but encoding stuff that isn't a reference. Commented Aug 22, 2016 at 15:30
  • @Zaid Much obliged. Commented Aug 23, 2016 at 9:17

1 Answer 1

4

I assume you're using either JSON or JSON::XS.

Both allow for non-reference data, but not via the procedural encode_json routine.

You'll need to use the object-oriented approach:

use strict;   # obligatory
use warnings; # obligatory

use JSON::XS;

my $encoder = JSON::XS->new();

$encoder->allow_nonref();
print $encoder->encode('Hello, world.');
# => "Hello, world."
Sign up to request clarification or add additional context in comments.

Comments

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.