iWantToLearn
iWantToLearn

Reputation: 79

change number to english Perl

Hye, Can you check my script where is my problem..sorry I'm new in perl..I want to convert from number to english words for example 1400 -> one thousand four hundred...I already used

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

this is my input file.txt

I have us dollar 1200 

and the output should be. "I have us dollar one thousand two hundred"

this is my script

#!/usr/bin/perl

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

if(! open(INPUT, '< snuker.txt'))
{
die "cannot opent input file: $!";
}

select OUTPUT;

while($lines = <INPUT>){

$lines =~ s/usd|USD|Usd|uSd|UsD/us dollar/g;
$lines =~ s/\$/dollar /g;
$lines =~ s/rm|RM|Rm|rM/ringgit malaysia /g;
$lines =~ s/\n/ /g; 
$lines =~ s/[[:punct:]]//g;
$lines =~ s/(\d+)/num2en($lines)/g; #this is where it should convert to english words
    print lc($lines); #print lower case
}

close INPUT;
close OUTPUT;
close STDOUT;

the output i got is "i have us dollar num2en(i have us dollar 1200 )"

thank you

Upvotes: 0

Views: 334

Answers (3)

zoul
zoul

Reputation: 104065

You’re missing the e modifier on the regex substitution:

$ echo foo 42 | perl -pe "s/(\d+)/\$1+1/g"
foo 42+1
$ echo foo 42 | perl -pe "s/(\d+)/\$1+1/ge"
foo 43

See man perlop:

Options are as with m// with the addition of the following replacement specific options:
        e    Evaluate the right side as an expression.

Plus you have to refer to the captured number ($1), not the whole string ($lines), but I guess you have already caught that.

Upvotes: 5

perreal
perreal

Reputation: 98048

You need to refer to the capture using $1 instead of passing the $lines in your last regex where you also need an e flag at the end so that it is evaluated as an expression. You can use i flag to avoid writing all combinations of [Uu][Ss][Dd]...:

while($lines = <INPUT>){
  $lines =~ s/usd/us dollar/ig;
  $lines =~ s/\$/dollar /g;
  $lines =~ s/rm/ringgit malaysia /ig;
  $lines =~ s/\n/ /g; 
  $lines =~ s/[[:punct:]]//g;
  $lines =~ s/(\d+)/num2en($1)/ge; #this is where it should convert to english words
  print lc($lines), "\n"; #print lower case
}

Upvotes: 7

Jenny D
Jenny D

Reputation: 1245

The problem here is that you are confusing regexps with functions. In the line where you try to do the conversion, you're not calling the function num2en; instead, you're replacing the number with the text num2en($line). Here's a suggestion for you:

($text, $number) = $lines =~ s/(.*)+(\d+); # split the line into a text part and a number part
print lc($text . num2en($number));         # print first the text, then the converted number;

Upvotes: 0

Related Questions