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

可紊 提交于 2019-12-03 16:08:18

问题


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.


回答1:


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';
}



回答2:


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;
  }
  ...
}



回答3:


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



回答4:


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');
}



回答5:


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];


来源:https://stackoverflow.com/questions/11369907/how-do-i-retrieve-an-integers-ordinal-suffix-in-perl-like-st-nd-rd-th

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!