perl - how to create an array with n empty strings or zeros?
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))]);
I know how to write a function, but I never do it in 10-line scripts.
Use the multiplier.
my @arr = ("") x $n;
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;
精彩评论