2009-08-18 32 views
6

Necesito un código en mi programa que toma un número como entrada y lo convierte en el texto correspondiente, p. 745 a "setecientos cuarenta y cinco".¿Cómo puedo convertir un número en texto en Perl?

Ahora, puedo escribir el código para esto, pero ¿hay alguna biblioteca o código existente que pueda usar?

+1

trabajando en un problema Proyecto Euler, verdad? – dala

+0

relacionado: http://stackoverflow.com/questions/309884/code-golf-number-to-words –

Respuesta

17

De perldoc de Lingua::EN::Numbers:

use Lingua::EN::Numbers qw(num2en num2en_ordinal); 

my $x = 234; 
my $y = 54; 
print "You have ", num2en($x), " things to do today!\n"; 
print "You will stop caring after the ", num2en_ordinal($y), ".\n"; 

impresiones:

You have two hundred and thirty-four things to do today! 
You will stop caring after the fifty-fourth. 
1

Usted puede intentar algo como esto:

#!/usr/bin/perl 

use strict; 
use warnings; 

my %numinwrd = (
    0 => 'Zero', 1 => 'One', 2 => 'Two', 3 => 'Three', 4 => 'Four', 
    5 => 'Five', 6 => 'Six', 7 => 'Seven', 8 => 'Eight', 9 => 'Nine', 
); 

print "The number when converted to words is 745=>".numtowrd(745)."\n"; 

sub numtowrd { 
    my $num = shift; 
    my $txt = ""; 
    my @val = $num =~ m/./g; 

    foreach my $digit (@val) {  
    $txt .= $numinwrd{$digit} . " "; 
    } 

    return $txt; 
} 

La salida es:

The number when converted to words is 745=>Seven Four Five 
+0

Para convertir '@ val' a' $ txt', podría ser más fácil hacer '$ txt = join" " , map {$ numinwrd {$ _}} @ val', haciendo efectivamente que su sub sea un trazador de líneas. Además, esta solución no produce 'setecientos cuarenta y cinco'. – amon

+0

Puede dar el código si puede hacer que la salida sea setecientos cuarenta y cinco – user1613245

Cuestiones relacionadas