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.
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 .
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.
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.
$#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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With