regexperlperl-moduleperl-data-structures

How do I retrieve an integer's ordinal suffix in Perl (like st, nd, rd, th)


I have number and need to add the suffix: 'st', 'nd', 'rd', 'th'. So for example: if the number is 42 the suffix is 'nd' , 521 is 'st' and 113 is 'th' and so on. I need to do this in perl. Any pointers.


Solution

  • Try this:

    my $ordinal;
    if ($foo =~ /(?<!1)1$/) {
        $ordinal = 'st';
    } elsif ($foo =~ /(?<!1)2$/) {
        $ordinal = 'nd';
    } elsif ($foo =~ /(?<!1)3$/) {
        $ordinal = 'rd';
    } else {
        $ordinal = 'th';
    }