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

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

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

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-16 14:07

    Using List::Flatten seems like the easiest:

    use List::Flatten;
    
    my @foo = (1, 2, [3, 4, 5], 6, [7, 8], 9);        
    my @bar = flat @foo;  # @bar contains 9 elements, same as (1 .. 9)
    

    Actually, that module exports a single simple function flat, so you might as well copy the source code:

    sub flat(@) {
        return map { ref eq 'ARRAY' ? @$_ : $_ } @_;
    }
    

    You could also make it recursive to support more than one level of flattening:

    sub flat {  # no prototype for this one to avoid warnings
        return map { ref eq 'ARRAY' ? flat(@$_) : $_ } @_;
    }
    

提交回复
热议问题