Geo1986
Geo1986

Reputation: 65

Perl arrays and arrayrefs

I am migrating environments and have code that is duplicated across both environments. When I call Dumper on the same part of the code in both environments I get two different outputs.

First environment

'key' => 'ARRAY(0x7f867b846850)', # Array contains element 'expected element'

Second environment

'key' => [ 'expected element' ],

I've seen other posts that suggests these are both ArrayRefs and can be regarded and treated as the same, is that the case? I haven't put the details of how the array is created as it's not what I'm investigating at the minute, I just want to know if these are identical, and why Dumper might treat them different.

Thanks

Upvotes: 0

Views: 58

Answers (1)

Sobrique
Sobrique

Reputation: 53478

Actually, that implies that your array reference is being turned into a string before being placed in the hash. A hash element is always an array reference, not an array. Dumper automatically traverses references.

In your first example it looks like the text you get when you convert a reference to a string. I guess just quoting the ref or concatenation would do it.

Something like this should illustrate the point I think?

#!/usr/bin/env perl

use strict;
use warnings;
use Data::Dumper;

my $array_ref = [ 1, 2, 3 ];

print Dumper $array_ref; 
print $array_ref -> [0],"\n";

#because we concat here, perl converts it to a string
$array_ref .= "";
print Dumper $array_ref;
#so this errors
print $array_ref -> [0],"\n";

Upvotes: 3

Related Questions