in reply to Re^2: adding st,nd,rd and th to numbers
in thread adding st,nd,rd and th to numbers

While the existing Lingua module is probably the best solution, I thought I'd add to your list of styles a subroutine that I've used in the past:
sub ordinate ($) { my $num = shift; $num =~ s/(\d*(11|12|13|4|5|6|7|8|9|0))$/$1th/ or $num =~ s/(\d*(1))$/$1st/ or $num =~ s/(\d*(2))$/$1nd/ or $num =~ s/(\d*(3))$/$1rd/; return $num; }

So, just out of curiosity, I benchmarked the alternatives above and my code. I don't test your first chunk of code, I start with the first example using the if/elsif/else structure. Results:

Rate Ordinate Method 3 Method 4 Method 2 Method 1 Ordinate 125/s -- -48% -50% -54% -64% Method 3 242/s 93% -- -4% -11% -30% Method 4 252/s 102% 5% -- -7% -27% Method 2 272/s 117% 13% 8% -- -21% Method 1 344/s 175% 42% 36% 27% --

It looks like your first pass at if/elsif/else is the best by quite a bit, and my approach is extremely slow. ;-) The code I used for benchmarking:

#!/usr/bin/perl -w use strict; use Benchmark qw(:all :hireswallclock); cmpthese( 2000, { 'Method 1' => 'for (0..300) { my $ord = method_1($_) }', 'Method 2' => 'for (0..300) { my $ord = method_2($_) }', 'Method 3' => 'for (0..300) { my $ord = method_3($_) }', 'Method 4' => 'for (0..300) { my $ord = method_4($_) }', 'Ordinate' => 'for (0..300) { my $ord = ordinate($_) }', }); sub ordinate { my $num = shift; $num =~ s/(\d*(11|12|13|4|5|6|7|8|9|0))$/$1th/ or $num =~ s/(\d*(1))$/$1st/ or $num =~ s/(\d*(2))$/$1nd/ or $num =~ s/(\d*(3))$/$1rd/; return $num; } sub method_1 { my $suffix; my $nouser = shift; if ($nouser =~ /(?<!1)1$/) { $suffix = 'st'; } elsif ($nouser =~ /(?<!1)2$/) { $suffix = 'nd'; } elsif ($nouser =~ /(?<!1)3$/) { $suffix = 'rd'; } else { $suffix = 'th'; } return $nouser.$suffix; } sub method_2 { my $suffix; my $nouser = shift; local *_ = \$nouser; if (/(?<!1)1$/) { $suffix = 'st'; } elsif (/(?<!1)2$/) { $suffix = 'nd'; } elsif (/(?<!1)3$/) { $suffix = 'rd'; } else { $suffix = 'th'; } return $nouser.$suffix; } sub method_3 { my $suffix; my $nouser = shift; foreach ($nouser) { if (/(?<!1)1$/) { $suffix = 'st'; } elsif (/(?<!1)2$/) { $suffix = 'nd'; } elsif (/(?<!1)3$/) { $suffix = 'rd'; } else { $suffix = 'th'; } } return $nouser.$suffix; } sub method_4 { my $suffix; my $nouser = shift; foreach ($nouser) { /(?<!1)1$/ && do { $suffix = 'st'; last }; /(?<!1)2$/ && do { $suffix = 'nd'; last }; /(?<!1)3$/ && do { $suffix = 'rd'; last }; $suffix = 'th'; } return $nouser.$suffix; }
<-radiant.matrix->
Larry Wall is Yoda: there is no try{} (ok, except in Perl6; way to ruin a joke, Larry! ;P)
The Code that can be seen is not the true Code