Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top