To get the last year in the "range," established by -
character, the cleanest way
my $year = (split /-/, $range)[-1];
If there isn't anything after the last delimiter then the last returned element by split
is what is before it, so the last element in its return list (obtained with index -1
) is either the second given year -- as in 2001-2020
-- or the only one, as in other examples. This performs no checking of input.
With a regex, one way is to seek the last number in the string
my ($year) = $range =~ /([0-9]+)[^0-9]*$/;
where if you use [0-9]{4}
then there is a small additional measure of checking.
The POSIX character class [[:digit:]]
and its negation [[:^digit:]]
(or \P{PosixDigit}
) can be used instead if desired, but note that these match all manner of Unicode "digit characters," just like \d
and \D
do (a few hundred), on top of the ascii [0-9]
(unless /a
modifier is used).
A full test program, for both
use warnings;
use strict;
use feature 'say';
my @ranges = qw(2018- 2001-2020 1999- 2005-);
foreach my $range (@ranges) {
my $year = (split /-/, $range)[-1];
# Or, using regex
# my ($year) = $range =~ /([0-9]+)[^0-9]*$/;
say $year;
}
Prints as desired.