Perl: What is the easiest way to flatten a multidimensional array?

后端 未结 7 1675
北荒
北荒 2020-12-16 13:27

What\'s the easiest way to flatten a multidimensional array ?

7条回答
  •  一个人的身影
    2020-12-16 14:09

    Same as Vijayender's solution but will work on mixed arrays containing arrayrefs and scalars.

    $ref = [[1,2,3,4],[5,6,7,8],9,10];
    @a = map { ref $_ eq "ARRAY" ? @$_ : $_ } @$ref;
    print "@a"
    

    Of course you can extend it to also dereference hashrefs:

    @a = map { ref $_ eq "ARRAY" ? @$_ : ref $_ eq "HASH" ? %$_: $_ } $@ref;
    

    or use grep to weed out garbage:

    @a = map { @$_} grep { ref $_ eq 'ARRAY' } @$ref;
    

    As of List::MoreUtils 0.426 we have an arrayify function that flattens arrays recursively:

    @a = (1, [[2], 3], 4, [5], 6, [7], 8, 9);
    @l = arrayify @a; # returns 1, 2, 3, 4, 5, 6, 7, 8, 9
    

    It was introduced earlier but was broken.

提交回复
热议问题