Keith Broughton
Keith Broughton

Reputation: 487

Declaring an array with incremental values in Perl

I know it's possible to declare an array like this:

my @array = ( 5 .. 10 );

which is equivalent to:

my @array = ( 5, 6, 7, 8, 9, 10 );

but is there a similar shorthand when the incremental value is greater than one e.g.

my @array = ( 5, 10, 15, 20, 25 );
my @array = ( 100, 200, 300, 400, 500 );

Upvotes: 8

Views: 3353

Answers (3)

Joakim
Joakim

Reputation: 510

You can also use Damian Conway's List::Maker.

use List::Maker;
my @list = <0..100 x 5>;

Upvotes: 2

ikegami
ikegami

Reputation: 385839

my @array = map 5*$_, 1..5;

and

my @array = map 100*$_, 1..5;

Upvotes: 22

ysth
ysth

Reputation: 98398

More generally:

my $start = 5;
my $stop = 25;
my $increment = 5;
my @array = map $start+$increment*$_, 0..($stop-$start)/$increment;

or:

chomp(my @array = `seq $start $increment $stop`);

(Just kidding.)

Upvotes: 4

Related Questions