perl Join with array reference
Asked Answered
Y

1

7

I am new to perl.

I am trying to use join with a array reference, but it is not working.

Here is my code.

my $arr = {
     'items' => ('home', 'chair', 'table')
};

my $output = join(',', $arr->{'items'});

print $output;

It is printing

table

instead of

home,chair,table

Can someone help me in this regard?

Yonit answered 18/9, 2013 at 11:5 Comment(0)
K
21

In Perl, parens do not create arrays. They only ever sort out precedence. The hashref

{ 'items' => ('home', 'chair', 'table') }

is the same as

{ 'items' => 'home', 'chair' => 'table' }

If you want to put an array into a hash, you need to use an arrayref, which you can create with [ ... ]:

my $hash = { 'items' => ['home', 'chair', 'table'] }

Now if you run your code, you'll get something like

ARRAY(0x1234567)

as output. This is the way references are printed out. We need to dereference it in order to join the elements. We can do so with the @{ ... } array dereference operator. Then:

print join(',', @{ $hash->{items} }), "\n";

To learn more about references and complex data structures in Perl, read

Katekatee answered 18/9, 2013 at 11:14 Comment(1)
Awesome answer with all the details I needed. Thanks amon. :)Yonit

© 2022 - 2024 — McMap. All rights reserved.