tanyeun has asked for the wisdom of the Perl Monks concerning the following question:

howdy monks :D,

I am trying to write a program
that will read a csv file from my bank
and sum up the money I spent during the month

the problem is some amount like "1,200.13", "1,105.02"
should add up to "2305.15", but instead
it's getting "2"!!!

I used an array to store the amounts like this
@ary = {"1,200.13", "1,105.02"}
an alternatives I came up with is like this:
Use Regular Expression to detect the ","
and then separate @ary to two :
@ary_basic = {"200.13", "105.02"}
@ary_1000 = {"1", "1"}
Then sum them up separately
But this solution only limits to amounts
that are less than 1 million.

Any better suggestions?

thx in advance :D

  • Comment on Regular Expression and digits problem(string, arithmetic)

Replies are listed 'Best First'.
Re: Regular Expression and digits problem(string, arithmetic)
by davido (Cardinal) on Apr 17, 2011 at 00:50 UTC

    Use a CSV parser so that you don't have to cook your own regular expressions for a job that a full blown parser is better at. Then it should be easier to find the numeric fields, and if necessary reformat them to look more like a number you can work with. Your home made CSV parser is obviously choking on the "commas as data versus commas as field separators" issue. It's already been solved. Text::CSV::Simple is one example of a parser that could simplify the process for you.


    Dave

      Thx Dave :D
      I will look into the csv parser.
      for now, Util's solution really got my job done :DDD
Re: Regular Expression and digits problem(string, arithmetic)
by GrandFather (Saint) on Apr 16, 2011 at 23:30 UTC

    Show us the code you are using, not just little bits that you think may be interesting. Show a complete sample script that demonstrates the problem with a little sample data. You may find I know what I mean. Why don't you? helps with figuring out what we want to see.

    True laziness is hard work
      Thx for the teaching grandpa :D
      I will be more precise next time
Re: Regular Expression and digits problem(string, arithmetic)
by Util (Priest) on Apr 16, 2011 at 23:40 UTC

    Just remove the commas:

    my @ary = ( "1,200.13", "1,105.02" ); tr{,}{}d for @ary; print "@ary\n";
    output:
    1200.13 1105.02

      That was my first thought too, but the OP muttered something about CSV so there may be more to the story than just that. Pretty hard to tell without the OP's code though! And if the OP hasn't got that much right then there are bound to be other areas where a little help may be required.

      True laziness is hard work