Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl Join with array reference

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?

like image 541
Keen Sage Avatar asked Sep 18 '13 11:09

Keen Sage


1 Answers

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

  • perlreftut and then
  • perldsc.
like image 168
amon Avatar answered Sep 22 '22 01:09

amon