How do I retrieve an integer's ordinal suffix

2019-03-18 08:04发布

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.

5条回答
Rolldiameter
2楼-- · 2019-03-18 08:20

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';
}
查看更多
可以哭但决不认输i
3楼-- · 2019-03-18 08:26

Use Lingua::EN::Numbers::Ordinate. From the synopsis:

use Lingua::EN::Numbers::Ordinate;
print ordinate(4), "\n";
 # prints 4th
print ordinate(-342), "\n";
 # prints -342nd

# Example of actual use:
...
for(my $i = 0; $i < @records; $i++) {
  unless(is_valid($record[$i]) {
    warn "The ", ordinate($i), " record is invalid!\n"; 
    next;
  }
  ...
}
查看更多
兄弟一词,经得起流年.
4楼-- · 2019-03-18 08:27

Another solution (though I like the preexisting answers that are independent of using modules better):

use Date::Calc 'English_Ordinal';
print English_Ordinal $ARGV[0];
查看更多
贼婆χ
5楼-- · 2019-03-18 08:35

Try this brief subroutine

use strict;
use warnings;

sub ordinal {
  return $_.(qw/th st nd rd/)[/(?<!1)([123])$/ ? $1 : 0] for int shift;
}

for (42, 521, 113) {
  print ordinal($_), "\n";
}

output

42nd
521st
113th
查看更多
我只想做你的唯一
6楼-- · 2019-03-18 08:41

Here's a solution which I originally wrote for a code golf challenge, slightly rewritten to conform to usual best practices for non-golf code:

$number =~ s/(1?\d)$/$1 . ((qw'th st nd rd')[$1] || 'th')/e;

The way it works is that the regexp (1?\d)$ matches the last digit of the number, plus the preceding digit if it is 1. The substitution then uses the matched digit(s) as an index to the list (qw'th st nd rd'), mapping 0 to th, 1 to st, 2 to nd, 3 to rd and any other value to undef. Finally, the || operator replaces undef with th.

If you don't like s///e, essentially the same solution could be written e.g. like this:

for ($number) {
    /(1?\d)$/ or next;
    $_ .= (qw'th st nd rd')[$1] || 'th';
}

or as a function:

sub ordinal ($) {
    $_[0] =~ /(1?\d)$/ or return;
    return $_[0] . ((qw'th st nd rd')[$1] || 'th');
}
查看更多
登录 后发表回答