Perl:展平多维数组的最简单方法是什么? [英] Perl: What is the easiest way to flatten a multidimensional array?
本文介绍了Perl:展平多维数组的最简单方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
扁平化多维数组的最简单方法是什么?
What's the easiest way to flatten a multidimensional array ?
推荐答案
使用 List::Flatten
似乎是最简单的:
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(@$_) : $_ } @_;
}
这篇关于Perl:展平多维数组的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文