2009-08-18 11 views
6

Ho bisogno di un codice nel mio programma che prende un numero come input e lo converte in testo corrispondente, ad es. 745 a "settecento quarantacinque".Come posso convertire un numero in testo in Perl?

Ora posso scrivere codice per questo, ma è possibile utilizzare una libreria o un codice esistente?

+1

Lavorare su un problema di Eulero progetto, voi? – dala

+0

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

risposta

17

Da perldoc di 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"; 

stampe:

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

Si può provare qualcosa di simile:

#!/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; 
} 

L'output è:

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

Per convertire '@ val' in' $ txt', potrebbe essere più facile fare '$ txt = join" " , mappa {$ numinwrd {$ _}} @ val', rendendo efficacemente il tuo sottotitolo. Inoltre, questa soluzione non produce "settecentoquarantacinque". – amon

+0

Puoi dare il codice se puoi produrre l'output a settecentoquarantacinque – user1613245

Problemi correlati