将阿拉伯数字转换成罗马数字 (Perl版本)

#use warnings;

use strict;
use Switch;

my @set=('M','D','C','L','X','V','I');

while(<STDIN>)
{
    chomp;
    my $number=$_;
    my $i=0;
    my @array;
    my $result;
    if($number=~ m/^[1-3]??(?(?<=^)[1-9]|\d){0,3}$/)
    {
        $number=sprintf "%4d",$number;
        my @num=split "",$number;
        foreach my $num (@num)
        {
            unless(($num eq ' ')||($num eq '0')){
                switch($i)
                {
                    case 0
                    {
                        @array=convert('','',$set[0]);
                    }
                    case 1
                    {
                        @array=convert($set[0],$set[1],$set[2]);
                    }
                    case 2
                    {
                        @array=convert($set[2],$set[3],$set[4]);
                    }
                    case 3
                    {
                        @array=convert($set[4],$set[5],$set[6]);
                    }
                }
                $result.=$array[$num-1];
            }
            $i++;
        }
        print "$result\n";
        
    }else
    {
        print "Please input a number between 1 and 3999\n";    
    }
}

sub convert
{
    my($first,$second,$third)=@_;
    my ($temp,@res);
    foreach(1..9)
    {
        if($_<4)
        {
            $temp="$third"x"$_";
        }
        elsif($_ == 4)
        {
            $temp=$third.$second;
        }
        elsif($_<9)
        {
            my $time=$_-5;
            $temp=$second."$third"x"$time";
        }else
        {
            $temp=$third.$first;
        }
        push @res,$temp;
    }
    return @res;
}


作者: icybay   发布时间: 2010-11-30