Skip to content

Instantly share code, notes, and snippets.

@ldante86
Created January 4, 2018 09:55
Show Gist options
  • Save ldante86/3581eb765b9b700ffc636ac606e1834e to your computer and use it in GitHub Desktop.
Save ldante86/3581eb765b9b700ffc636ac606e1834e to your computer and use it in GitHub Desktop.
Return the ordinal of a number
use strict;
use warnings;
use 5.010;
sub ordinal {
my $x = $_[0];
if ( $x <= 20 ) {
return $x . "st\n" if $x == 1;
return $x . "nd\n" if $x == 2;
return $x . "rd\n" if $x == 3;
return $x . "th\n" if ( $x == 0 ) or ( $x >= 4 and $x <= 20 );
}
else {
my $len = substr( $x, length($x) - 2, 2 );
return $x . "th\n" if $len == 11;
return $x . "th\n" if $len == 12;
return $x . "th\n" if $len == 13;
$len = substr( $x, length($x) - 1 );
return $x . "st\n" if $len == 1;
return $x . "nd\n" if $len == 2;
return $x . "rd\n" if $len == 3;
return $x . "th\n" if $len == 0 or ( $len >= 4 and $len <= 9 );
}
}
print ordinal($ARGV[0]) if @ARGV;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment