如何在Perl中检索整数的序数后缀(如st,nd,rd,th)

boz*_*ser 14 regex perl perl-module perl-data-structures

我有数字,需要添加后缀:'st','nd','rd','th'.例如:如果数字为42,则后缀为'nd',521为'st',113为'th',依此类推.我需要在perl中执行此操作.任何指针.

Bil*_*ert 27

使用Lingua :: EN :: Numbers :: Ordinate.从概要:

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;
  }
  ...
}
Run Code Online (Sandbox Code Playgroud)


Dan*_* Li 16

试试这个:

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

  • 即使有*CPAN解决方案,我也喜欢这个.它经过深思熟虑,高度可读,缺乏依赖性,并且与任何整数的CPAN解决方案一样准确. (4认同)
  • Upvote用于有效使用难以捉摸的零宽度负面后视断言.虽然(遗憾地)正如Bill Ruppert指出的那样,已经有了一个CPAN模块. (2认同)

Bor*_*din 7

试试这个简短的子程序

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";
}
Run Code Online (Sandbox Code Playgroud)

产量

42nd
521st
113th
Run Code Online (Sandbox Code Playgroud)