in reply to Re: (Ovid) Re: comparing two amounts of money.
in thread comparing two amounts of money.

Your insticts were correct to use if ( $var1 > $var2 ) {...}. Let me explain this in a bit more detail.

Perl's typing is based around data structures (scalars, arrays, hashes, etc) and not data types. Other languages that use typing typically use things like int, float, char, etc. Perl also deals with things like that, but does it behind the scenes. When dealing with a string, if you try to perform mathematical operations on it, Perl will (usually¹) try to convert the string to a number and perform the mathematical operations. If a string can't be converted to a number, it's considered to be "zero". For example, here's a little blow to my ego:

$ perl -e 'print "Ovid" + 0' 0

When you try to compare a string with a dollar sign, Perl sees the dollar sign and just converts the string to a zero. For my example above, you may have been mislead (my $apologies). When comparing strings, you would use the string comparison operators such as gt, ge, lt, and le. However, since those are comparing strings and not numbers, your results will not be suitable for mathematical operations.

So, Perl will not "crash" when you have a "." or "," in your string. The period will be recognized as a decimal point. There is one thing to be wary of, though: when trying to convert a string to a number, Perl still take the numbers at the beginning of string and use those:

$ perl -e 'print "123Ovid" + 4' 127

So, you either need to strip those dollar signs from your strings or not add those dollar signs until you're ready to output them to a file, report, screen, etc.

Cheers,
Ovid

1. The unary increment (++) and (--) decrement operators are counter-examples.

Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.