Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an array of n elements

Tags:

perl

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.

like image 210
G4143 Avatar asked Mar 18 '20 17:03

G4143


People also ask

How do you create an array of n elements?

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.

How do you create an array of n elements in C++?

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];

How do you create an array of n numbers in Java?

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.

How do you create an array?

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.


1 Answers

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.

like image 94
Andy Lester Avatar answered Oct 06 '22 22:10

Andy Lester