Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Perl

Idiom #314 Fill array with value

Set all the elements in the array x to the same value v

my @x = (undef) x $n; 

foreach (@x) { $_ = $v }

Create a list with $n elements, each initialized to undef. Then assign $v to each element.
my @x = ($v) x $n;

This defines a new list (@x) and sets $n elements of it to $v. The list grows to length $n. The x operator in this context repeats the left operand $n times.
#include <array>
x.fill(v);

New implementation...