Search code examples
perlmultiplication

Perl - multiply decimal


When the results come out, it gives the wrong results if I multiply it by (0.62). But if I multiply it by a whole number (1 or 2 ) is okay. How do I do decimal multiplication?

Input
*****

HEADER
  GAME
     BALL X1 ;
     GOOD CATCH 1 5.6770 4.550 3.455 2.333 ;
     END
END

Output
******
HEADER
  GAME
     BALL X1 ;
     GOOD CATCH 1 3.5197.4 2.821 2.1421 1.4464.6 ;
     END
END


use strict ;

sub multiply {
    my ( $str ) = @_;

    $str =~ s/(GOOD CATCH.*?;)/_multiply($1)/ge;
    return $str;
}

sub _multiply {
    my ( $str ) = @_;

    $str =~ s/(\d\d+)/_mul_number($1)/ge;
    return $str;
}

sub _mul_number {
    my ($num) = @_;

    return $num * 2;
}

Solution

  • The regular expression $str =~ s/(\d\d+)/_mul_number($1)/ge; looks for (\d\d+) which will match a sequence of two or more digits, but not a decimal point. With decimal numbers, it will treat them as two separate numbers; for instance, given "12.34", it will separately process "12" and "34", giving "7.44" and "21.08", for a final result of "7.44.21.08". Which is probably not what you want.

    In order to handle decimal numbers in the input, you'll need to expand the regular expression to match them. A simple possibility would be ([\d.]+), that is: $str =~ s/([\d.]+)/_mul_number($1)/ge;

    A more complex regex could also make sure there's at most one decimal point (to reject "12.34.56") or allow + and/or - signs for positive and negative numbers.