The T-Files


Wed, 09 Jun 2010

The thousand and one reasons to love Perl: [20] Alphanumeric Ranges

After a long time, finally another Perl project, so here you go:

Perl has a range operator to help iterating over index ranges.

foreach ( 1 .. 10 ) { 
    # do something
}

foreach ($start .. $finish) {
	# do something
}

# get the last three array elements
# negative array indices are another of the 1001 reasons
my @array_slice = @array[ -3 .. -1];

Many languages have that, but Perl's version has a little extra magic to also work with letters, and not just numbers:

$ perl -le 'foreach ("F97" .. "G05"){ print }';
F97
F98
F99
G00
G01
G02
G03
G04
G05

In scalar context, the range operator works as a boolean bi-stable flip-flop, with some extra special magic thrown in if constant values are present, but that is getting a bit too arcane to be considered a great feature. I am not even going to try to explain it here, the Perl Monks have an article about it.