Create an array of n elements

Viewed 532

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.

2 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.

Less elegant way to fill an array with some value (for demonstration purpose only)

my $n = 8;
my @array;

$array[$n] = 0 while $n--;
Related