30

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.

1 Answer 1

54

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.