I'm looking for the Perlish way to create an array of n elements where each element is 0.
This is the best I could come up with:
#! /usr/bin/env perl
use warnings;
use strict;
use utf8;
use feature qw<say>;
print "Enter length of array: ";
chomp(my $len = <STDIN>);
my @arr = split // => "0" x $len;
say "@arr ", scalar(@arr);
I also look at List::Util's reduce but it wasn't as compact as the above snippet.
To create an array with N elements containing the same value: Use the Array() constructor to create an array of N elements. Use the fill() method to fill the array with a specific value. The fill method changes all elements in the array to the supplied value.
int n; cin >> n; int array[n]; But as we know this is not allowed in C++ and instead we can write this one, which will create the array in dynamic memory (i.e. heap): int n; cin >> n; int *array = new int[n];
Array Initialization in Java To use the array, we can initialize it with the new keyword, followed by the data type of our array, and rectangular brackets containing its size: int[] intArray = new int[10]; This allocates the memory for an array of size 10 . This size is immutable.
Obtaining an array is a two-step process. First, you must declare a variable of the desired array type. Second, you must allocate the memory to hold the array, using new, and assign it to the array variable. Thus, in Java, all arrays are dynamically allocated.
Perl's arrays expand as necessary. You don't have to create them up front. Why do you want to create an array of a defined length?
The way to do what you're asking is:
my @a = (0) x $n;
where $n
is the number of elements, but again, it might not be appropriate. Tell us more about what the problem is you're trying to solve.
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