arrays - How to use join? -


minimal code based on this answer , join statement

my @x = qw/10 20 30 40/; @y = qw/60 70 8 90 10/; @input_list = (@x, @y);  print "before join @input_list \n";  print join ",", @$_ @input_list ;  print "after join @input_list \n"; 

which gives

before join 20 40 60 80 120 140 16 180 20  after join 20 40 60 80 120 140 16 180 20  

but in use strict;

can't use string ("10") array ref while "strict refs" in use @ test4.pl line 10.

join joins separate strings of array in manual. here code tries join comma apparently each hash (@$_) of array item. however, seems happening.

why error here in minimum code?

ok, you're doing here:

print join ",", @$_ @input_list ; 

isn't working, because it's:

  • iterating @input_list extracting each element $_.
  • dereferencing $_ pretending it's array @$_.

this same trying to:

print join ( ",", @{"10"} ); 

which makes no sense, , doesn't work.

my $string = join ( ",", @input_list ); print $string;  

will trick.

the thing you're missing here think, this:

use data::dumper;  @x = qw/10 20 30 40/; @y = qw/60 70 8 90 10/; @input_list = (@x, @y); print dumper \@input_list; 

isn't generating multi-dimensional list. it's single dimensional one.

$var1 = [           '10',           '20',           '30',           '40',           '60',           '70',           '8',           '90',           '10'         ]; 

i suspect may want is:

my @x = qw/10 20 30 40/; @y = qw/60 70 8 90 10/; @input_list = (\@x, \@y); 

or perhaps:

my $x_ref = [ qw/10 20 30 40/ ]; $y_ref = [ qw/60 70 8 90 10/ ]; @input_list = ($x_ref, $y_ref ); 

which makes @input_list:

$var1 = [           [             '10',             '20',             '30',             '40'           ],           [             '60',             '70',             '8',             '90',             '10'           ]         ]; 

then 'for' loop works:

print join (",", @$_),"\n" @input_list ; 

because then, @input_list 2 items - 2 array references can dereference , join.

as slight word of warning though - 1 of gotchas can occur when doing:

my @input_list = (\@x, \@y); 

because you're inserting references @x , @y - if reuse either of these, you'll change content of @input_list - why it's better use my @input_list = ( $x_ref, $y_ref );.


Comments

Popular posts from this blog

Email notification in google apps script -

c++ - Difference between pre and post decrement in recursive function argument -

javascript - IE11 incompatibility with jQuery's 'readonly'? -