Lord of Grok
Lord of Grok

Reputation: 353

How to dereference this array? And how do I store this array into a hash?

I'm having some trouble getting around Perl's referencing and dereferencing, I'm coming from a C++ background, so I understand dereferencing and referencing. It's just that Perl's syntax has got me thrown for a tizzy.

I have this code where I'm trying to print the contents of $obj->{numbers}

my @arr = (1,2,3,4,5,6);

my $test = "" . join(',', @arr). "" || '';

my @my_arr = ();

@my_arr = split (',', $test);

my $obj->{numbers} = \@my_arr;

print $obj->{numbers};

This will print ARRAY(0x1ac9af8).

I'm expecting it to print something out like 1 2 3 4 5 6.

Also I want to store this array in a hash like so

my $this;
$this->{foo} = [ { bar => $obj->{numbers} } ];
print $this->{foo}[0];

This prints HASH(0x418b018). I also want this to print 1 2 3 4 5 6.

How would I be able to print this array within the hash?

Upvotes: 3

Views: 101

Answers (1)

toolic
toolic

Reputation: 62182

$obj->{numbers} returns a reference to an array, which is why you see something like ARRAY(0x1ac9af8) when you print it.

You can dereference the array using @{ }. For example:

print "@{ $obj->{numbers} }";

prints:

1 2 3 4 5 6

I used double quotes so that you would get a single space between each element of the array.

Similarly for the array in the hash:

print "@{ $this->{foo}[0]{bar} }";

See also perldsc

Upvotes: 5

Related Questions