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)
试试这个简短的子程序
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)