Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl - how to create an array with n empty strings or zeros?

Tags:

perl

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.

like image 615
agsamek Avatar asked Mar 16 '11 10:03

agsamek


People also ask

How do I create an empty array in Perl?

Since perl doesn't require you to declare or initialize variables, you can either jump right in and call push , or you can first create an empty list (by assigning the value () to the list), and then start using push .

How do you fill the rest of an array with zeros?

Use the fill() method to create an array filled with zeros, e.g. new Array(3). fill(0) , creates an array containing 3 elements with the value of 0 . The fill() method sets the elements in an array to the provided value and returns the modified array.

How do I declare an array in Perl?

Array Creation: In Perl programming every array variable is declared using “@” sign before the variable's name. A single array can also store elements of multiple datatypes.

What is $# array in Perl?

$#array is the subscript of the last element of the array (which is one less than the length of the array, since arrays start from zero). Assigning to $#array changes the length of the array @array, hence you can destroy (or clear) all values of the array between the last element and the newly assigned position.


1 Answers

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; 
like image 180
Tim Avatar answered Oct 05 '22 08:10

Tim