Logo

Programming-Idioms

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

Idiom #303 Array with non-default lower bound

Declare an array a of integers with six elements, where the first index is 42 and consecutive elements have the indices 43, 44, 45, 46, 47.

use feature 'say';
use Array::Base +42;

my @a = ('A'..'Z');

say $a[42]; # prints A
say $a[43]; # prints B

no Array::Base;  # restore indexing to base 0

Install CPAN module Array::Base for this. The base index of new arrays can be changed, and can be reset back to 0, anywhere in your code.

Perl once supported this via the built-in magic variable $[ but that has now been deprecated.
A : array (42 .. 47) of Integer;

A'First is 42, A'Last is 47, A'Length is 6.

New implementation...
< >
tkoenig