Web Development

Working with the range operator in Perl

Perl operators provide much-needed functionality and save precious keystrokes. One good example is the range operator. See how it can simplify the process of dealing with multiple values in lists and arrays.

By Charles Galpin

Perl has established itself as a valuable developer skill set. It greatly simplifies many tasks, and both its power and popularity continue to grow. Among its handy features is the range operator, which offers a shorthand method for working with arrays. This article will show you how you can put the range operator to work.

The range operator
Like many other Perl operators, the range operator (..) behaves differently depending on its context. In a list context, it produces the range of values from the left value through the right value in increments of 1.

Here is an example that prints out "1 2 3 4 5 6 7 8 9 10":
foreach (1 .. 10) {
  print "$_ ";
}


The range operator also works with strings. The following creates an array of the letters of the alphabet:
@alphabet = ('a' .. 'z');

In scalar context, .. returns a Boolean value, initially false. First, the left operand is evaluated. The return value remains false, as long as the left operand is false. Once the left operand is true, the operator returns true and continues to return true, as long as the right operand is evaluated. As soon as the right operand is true, the operator returns false again.

The range operator returns the empty string for false or a sequence number for true. The sequence number begins with 1, and the final number has E0 appended to it, allowing you to determine the end points easily.

Also, if both operands are constants, their value is compared to the current line number. This example prints the third through the fifth lines of a file:
if (3 .. 5) {
  print;
}


Here is a more useful example of the range operator’s power:
if (/start/ .. /end/) {
  print;
}


This example will start printing lines that contain the string start and continue to do so until a line containing end is processed.

Perl has more operators than most languages, and these operators tell the system what action to perform. The range operator is just one of them, which provides needed functionality with only a few keystrokes.
0 comments