http://www.perlmonks.org?node_id=1222668

kris1511 has asked for the wisdom of the Perl Monks concerning the following question:

I have array in format
my @groups = [ [ 23 ], [ 22 ] ]; my $perms = join ',', @groups; print Dumper $perms;

It gives me result as array : $VAR1 = 'ARRAY(0x7f82c3792848)';

How can I flatten this kind of array into string. Thanks!!

Replies are listed 'Best First'.
Re: Joining array into new string
by poj (Abbot) on Sep 19, 2018 at 19:12 UTC
    #!perl use strict; use Data::Dumper; #my @groups = [ [ 23,24,25 ], [ 22,21,20 ] ]; # change ^ ^ my @groups = ( [ 23,24,25 ], [ 22,21,20 ] ); my $perms = join ',', map { join ',', @$_ } @groups ; print Dumper $perms;
    poj

      ++, but please explain the actual problem. Pointers are fine (I use them all the time), but denote them with an explanation of what you mean in human terms.

      Even if OP gets the point (no pun intended), others reading this may not.

        To be fair to poj, The question he originally asked is "how can I" not "why doesn't it work?"

        For the benefit of others: The OP created an outer anonymous array containing two other inner anonymous arrays by using the square brackets. From the @groups array perspective, it only contains a single element, the outer anonymous array. It doesn't "see" the other anonymous arrays inside of it. When you try to join on an array with a single element, you just get the single element returned because there's nothing really to join. The ARRAY(0x...) you see is the string that perl spits out when you print an anonymous array. It represents the location of the array in the computer's memory (I think Perl's virtual machine's memory, to be more precise).

        $PM = "Perl Monk's";
        $MCF = "Most Clueless Friar Abbot Bishop Pontiff Deacon Curate Priest";
        $nysus = $PM . ' ' . $MCF;
        Click here if you love Perl Monks

Re: Joining array into new string
by tybalt89 (Monsignor) on Sep 19, 2018 at 21:09 UTC
    #!/usr/bin/perl # https://perlmonks.org/?node_id=1222668 use strict; use warnings; sub flatten { map ref($_) ? flatten(@$_) : $_, @_ } my @groups = [ [ 23 ], [ 22 ] ]; # note, single item array :) my $perms = join ',', flatten(@groups); print "$perms\n"; # more complex example @groups = ( [ 20, 21, [22, 23], 24], [ [ 25 ], [ [ [ 26 ] ] ] ], 27 ); $perms = join ',', flatten(@groups); print "$perms\n";

    Outputs:

    23,22 20,21,22,23,24,25,26,27
Re: Joining array into new string
by AnomalousMonk (Archbishop) on Sep 19, 2018 at 21:43 UTC