in reply to Chomp Maybe?

A couple points:

When using DBI and prepare, use placeholders. If you don't know what they are, read the doc. To put it simply, you can put a ? in the prepare statement, pass values for each in the execute, and it will properly quote it for you. In your case, something like this

my $dbh = $db->prepare("SELECT balance FROM Table1 WHERE username=? an +d balance < '-.01'"); $dbh->execute($authuser); my ($balance_due) = $dbh->fetchrow_array;
would work. This is good for untrusted data.

Anyway, the easiest solution to your problem would be to simply negate the value, which would yield a positive. So something like

$balance_due = -$balance_due # or $balance_due = $balance_due * -1;
would be good and result in $balance_due being equal to 9.99.

To answer your question using a different way, you could also use a substitution regex

$balance_due =~ s/-//;
to strip out (literally replace it with nothing) the first - it finds. If you don't understand what it going on, read up on perlretut.

Added Second paragraph.

Replies are listed 'Best First'.
Re: Re: Chomp Maybe?
by hardburn (Abbot) on Jul 01, 2003 at 18:24 UTC

    Actually, I think it would be better to just get the absolute value:

    $balance_due = abs($balance_due);

    This protects you in the event that $balance_due is a positive number (which shouldn't happen according to the SQL, but I've always beleived that a good programmer is someone who looks both ways on a one way street). It's also close enough in speed to negation that random noise is a factor in execution time. Code:

    #!/usr/bin/perl use strict; use warnings; use Benchmark qw(cmpthese); my $data = -12345; my $count = pop || 500000; cmpthese($count, { negate => sub { my $i = -$data }, absolute => sub { my $i = abs($data) }, regex => sub { my ($i) = $data =~ s/-// }, });

    Results:

    Benchmark: timing 500000 iterations of absolute, negate, regex... absolute: 1 wallclock secs ( 1.24 usr + 0.00 sys = 1.24 CPU) @ 40 +4858.30/s (n=500000) negate: 1 wallclock secs ( 1.15 usr + 0.00 sys = 1.15 CPU) @ 43 +3275.56/s (n=500000) regex: 3 wallclock secs ( 3.16 usr + 0.00 sys = 3.16 CPU) @ 15 +8328.06/s (n=500000) Rate regex absolute negate regex 158328/s -- -61% -63% absolute 404858/s 156% -- -7% negate 433276/s 174% 7% --

    ----
    I wanted to explore how Perl's closures can be manipulated, and ended up creating an object system by accident.
    -- Schemer

    Note: All code is untested, unless otherwise stated

      ++, you're absolutely right. When writing up my node, I forgot all about just getting the absolute value. ; )
Re: Re: Chomp Maybe?
by th3monk3y (Novice) on Jul 01, 2003 at 04:52 UTC
    Works like a charm! You guys are awesome! Thanks for your prompt reply! Regards, -Paul