Jump to content

How to Work with Roman Numerals in Perl

+ 4
  gnat's Photo
Posted Oct 20 2009 03:30 PM

If you want to convert between regular numbers and Roman numerals, use the Roman module from CPAN:

use Roman;
$roman = roman($arabic);                        # convert to roman numerals
$arabic = arabic($roman) if isroman($roman);    # convert from roman numerals


The Roman module provides both Roman and roman for converting Arabic ("normal") numbers to their Roman equivalents. Roman produces uppercase letters, whereas roman gives lowercase ones.</p><p>The module only deals with Roman numbers from 1 to 3999, inclusive. The Romans didn't represent negative numbers or zero, and 5000 (which 4000 is represented in terms of) uses a symbol outside the ASCII character set.

use Roman;
$roman_fifteen = roman(15);                         # "xv"
print "Roman for fifteen is $roman_fifteen\n";
$arabic_fifteen = arabic($roman_fifteen);
print "Converted back, $roman_fifteen is $arabic_fifteen\n";


Roman for fifteen is xv
Converted back, xv is 15


Or to print the current year:

use Time::localtime;
use Roman;
printf "The year is now %s\n", Roman(1900 + localtime->year);


The year is now MMIII


Now, if you happen to have Unicode fonts available, you'll find that code points U+2160 through U+2183 represent Roman numerals, including those beyond the typical ASCII values.

use charnames ":full";
print "2003 is", "\N{ROMAN NUMERAL ONE THOUSAND}" x 2, "\N{ROMAN NUMERAL THREE}\n";


2003 is Ⅿ Ⅿ Ⅲ


However, the Roman module doesn't yet have an option to use those characters.

Believe it or not, there's even a CPAN module that lets you use Roman numerals in arithmetic.

use Math::Roman qw(roman);
print $a  = roman('I'); #  I
print $a += 2000;       #  MMI
print $a -= "III";      #  MCMXCVIII
print $a -= "MCM";      #  XCVIII


Perl Cookbook

Learn more about this topic from Perl Cookbook, 2nd Edition.

Find a Perl programmer, and you'll find a copy of Perl Cookbook nearby. Perl Cookbook is a comprehensive collection of problems, solutions, and practical examples for anyone programming in Perl. The book contains hundreds of rigorously reviewed Perl "recipes" and thousands of examples ranging from brief one-liners to complete applications.

The second edition of Perl Cookbook has been fully updated for Perl 5.8, with extensive changes for Unicode support, I/O layers, mod_perl, and new technologies that have emerged since the previous edition of the book. Recipes have been updated to include the latest modules. New recipes have been added to every chapter of the book, and some chapters have almost doubled in size.

See what you'll learn


Tags:
0 Subscribe


0 Replies