perl - 如何创建一个包含 n 个空字符串或零的数组? [英] perl - how to create an array with n empty strings or zeros?

查看:79
本文介绍了perl - 如何创建一个包含 n 个空字符串或零的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在 Perl 中操作 CSV 文件时,我经常需要用一定数量的相同元素初始化一个数组:

When I manipulate CSV files in Perl I often have a need to initialize an array with some number of same elements:

my $arr = [];
for my $i (0..$n-1) {
    push @$arr, "";
}

有没有办法以更紧凑的形式做到这一点?

Is there a way to do it in a more compact form?

完美地我想要一个用于此目的的表达式,以便我可以轻松添加缺失的列:

Perfectly I would like to have an expression for this purpose, so that I can add missing columns easily:

f([@$some_tab, n_elems("", $column_number - scalar(@$some_tab))]);

我知道如何编写函数,但我从不使用 10 行脚本编写.

I know how to write a function, but I never do it in 10-line scripts.

推荐答案

使用乘数.

my @arr = ("") x $n;

更新:请注意,这会复制元素,如果您使用引用填充数组,这可能是不可取的.在这种情况下,需要构造每个元素,您可以使用 map:

Update: note that this duplicates the element, which might not be desirable if you are filling the array with references. In such a case, where each element needs to be constructed, you could use a map:

my @arr = map { [] } 1..$n;

这篇关于perl - 如何创建一个包含 n 个空字符串或零的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆