Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to produce range with step in Perl

Tags:

perl

In Bash, seq 5 5 20 produces 5 10 15 20.

In Perl, 1..5 produces 1 2 3 4 5; does it support step?

How do I produce a range with step in Perl?

like image 951
Matt Avatar asked Jan 11 '12 13:01

Matt


People also ask

What is range operator in Perl?

In Perl, range operator is used for creating the specified sequence range of specified elements. So this operator is used to create a specified sequence range in which both the starting and ending element will be inclusive. For example, 7 .. 10 will create a sequence like 7, 8, 9, 10.

Which operator can be used to define range?

You can use the range operator to create a list with zero-filled numbers. To create an array with ten elements that include the strings 01, 02, 03, 04, 05, 06, 07, 08, 09, and 10 do: @array = ("01".."10"); And you can use variables as operands for the range operator.

What is $@ in Perl?

$@ The Perl syntax error or routine error message from the last eval, do-FILE, or require command. If set, either the compilation failed, or the die function was executed within the code of the eval.


2 Answers

perldoc -f map is one way:

use warnings; use strict; use Data::Dumper;  my @ns = map { 5 * $_ } 1 .. 4; print Dumper(\@ns);  __END__  $VAR1 = [           5,           10,           15,           20         ]; 

See also: perldoc perlop

like image 188
toolic Avatar answered Oct 02 '22 18:10

toolic


The range operator in Perl doesn't support steps. You could use a for loop instead:

for (my $i = 5; $i <= 20; $i += 5) {     print "$i\n"; } 
like image 28
Eugene Yarmash Avatar answered Oct 02 '22 18:10

Eugene Yarmash