I ran across an old function I had written to take a non-negative integer and append the correct ordinal suffix. (I.e. 'th', 'st', 'nd', or 'rd') Out of boredom, I started golfing. Here's an early attempt coming in at 70 strokes:

sub num2ord2 { my $n = shift; # 1 2 3 4 5 6 +7 # 12345678901234678901234567890123456789012345678901234567890123456789 +0 $n.(qw(th st nd rd),('th')x16,((qw(th st nd rd),('th')x6)x8))[$n%100 +] }

But... I can do it in 40... Can you beat that?

† It does generate a warning, however.

-sauoq
"My two cents aren't worth a dime.";

Replies are listed 'Best First'.
Re: Golf - Ordinal Suffixes
by japhy (Canon) on Oct 27, 2005 at 02:51 UTC
    Here's my first crack, coming in at 53.
    sub num2ord { my $n = shift; # 1 2 3 4 5 6 +7 # 12345678901234678901234567890123456789012345678901234567890123456789 +0 $n.($n=~/1.$/?'th':qw(th st nd rd)[$n=~/([123]?)$/]) }
    Update: and here's my 40-char entry:
    sub num2ord { my $n = shift; # 1 2 3 4 5 6 +7 # 12345678901234678901234567890123456789012345678901234567890123456789 +0 $n.(qw(th st nd rd)[$n=~/(1?\d)$/]||th) }
    It's not strict-safe, and will throw a warning if warnings are turned on. And I can trim one more character off, but I'll leave that up to you to find!

    Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
    How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart

      Very nice. Here's my 40 chars... It runs under strict, anyway...

      sub num2ord { local $_ = shift; # 1 2 3 4 5 6 +7 # 12345678901234678901234567890123456789012345678901234567890123456789 +0 $_.qw(th st nd rd)[/(?<!1)([123])$/*$1] }
      And, combining ours can get us down to 35...

      -sauoq
      "My two cents aren't worth a dime.";
      
        Your way to shave a character (/msg'd) and my way are different, thus we can get it down to 34:
        sub num2ord { local $_ = shift; # 1 2 3 4 # 123456789012346789012345678901234567890 $_.(qw(0 st nd rd)[/1?\d$/g]||th) }

        Jeff japhy Pinyan, P.L., P.M., P.O.D, X.S.: Perl, regex, and perl hacker
        How can we ever be the sold short or the cheated, we who for every service have long ago been overpaid? ~~ Meister Eckhart
Re: Golf - Ordinal Suffixes
by zshzn (Hermit) on Oct 27, 2005 at 23:05 UTC
    use Lingua::EN::Numbers::Ordinate; sub num2ord { my $n = shift; ordinate($n); }

      # 1 2 3 4 5 6 +7 # 12345678901234678901234567890123456789012345678901234567890123456789 +0 use Lingua::EN::Numbers::Ordinate;
      With that overhead, you can't win... ;-)

      -sauoq
      "My two cents aren't worth a dime.";