2

I have tried, I have searched in the internet and I am out of ideas at this moment. I have an array which has elements. I use to Dumper function to ensure that the elements are present however, when I try to access individual items, I don't get the expected output.

And someone please help.

This is the code

print "<pre>Array: ".Dumper(@configFiles)."\n";
print "First: ".$configFiles[0]."\n";
print "Second: ".$configFiles[1]."</pre>";

Below is the output

Array: $VAR1 = [
      'searchTables.json',
      'NAM_database.json'
    ];

First: ARRAY(0x9a8f60)
Second:   

In case you are wondering how were the array elements assigned, I read a json file then converted it with the function below.

sub parseJson{
    my ($jfilename) = @_;
    if(-e "$jsoncPath/$jfilename"){
        return decode_json($json_data);
    }else{

    }
}

See the json below

[
   "searchTables.json",
   "NAM_database.json"
]

I also tried de-referencing as seen below with no success

print "<pre>First: ".@{$configFiles[0]}."</pre>";

give me what is sceen below.

First: 2
2
  • Tip: If you want to dump an array or hash, best to pass a reference. Dumper(\@configFiles). Commented Aug 28, 2014 at 14:52
  • Thanks for that note, this provide a better picture of what is within the array. Commented Aug 28, 2014 at 15:21

2 Answers 2

3

decode_json returns a reference to an array not the actual array. Should be:

my $configFiles = parseJson($jfilename);
print "<pre>Array: " . Dumper($configFiles) . "\n";
print "First: " . $configFiles->[0] . "\n";
print "Second: " . $configFiles->[1] . "</pre>";

or

print "<pre>Array: " . Dumper(@configFiles) . "\n";
print "First: " . $configFiles[0][0] . "\n";
print "Second: " . $configFiles[0][1] . "</pre>";
Sign up to request clarification or add additional context in comments.

2 Comments

This worked $configFiles[0]->[0] and also the following @{$configFiles[0]}[0]
$configFiles[0]->[0] can be shortened to $configFiles[0][0]
2

The @configFiles is not the array you think/expect. The first element is an array reference, you need to dereference it to access the array:

print "ARRAY: @{$configFiles[0]}\n";

3 Comments

I tried this with no success print "<pre>First: ".@{$configFiles[0]}."</pre>"; give me what is sceen below. First: 2
@AndreDixon In scalar context, an array returns its size, not its elements. Using the concatenation operator . puts an array in scalar context. If you just use interpolation you'd be fine: print "<pre>First: @{$configFiles[0]}</pre>"
Or just change your concatenation dot into a comma - print "<pre>First: ", @{$configFiles[0]}."</pre>";

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.