CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
math function in a while loop

 



jnamiyo
New User

Jul 21, 2014, 4:25 PM

Post #1 of 5 (486 views)
math function in a while loop Can't Post

HI Perl Gurru's been a while since Ive asked a question in here but I am getting back into programing with perl.

I have a db with product information including quantities and prices.

I want perl to do two things: multiply $stock * $price and then add each resulting line into a total price.

So while there is a line in the db the code will multiply the two columns, stock an price, then add each result until the db ends and return a grand total.

Any help will be greatly appreciated.


BillKSmith
Veteran

Jul 22, 2014, 6:48 AM

Post #2 of 5 (476 views)
Re: [jnamiyo] math function in a while loop [In reply to] Can't Post

Use modules included with your distribution of perl.


Code
use strict; 
use warnings;
use DBI;
use List::Util qw(sum);
my $dbh = 'Your code here';
my $sql = 'Your code here';
my $total_price = sum
map {$_->[0] * $_->[1]}
@{$dbh->selectall_array_ref($sql)};
print $total_price;

Good Luck,
Bill


jnamiyo
New User

Jul 22, 2014, 9:03 AM

Post #3 of 5 (470 views)
Re: [BillKSmith] math function in a while loop [In reply to] Can't Post

I think you meant selectall_arrayref


jnamiyo
New User

Jul 22, 2014, 9:05 AM

Post #4 of 5 (469 views)
Re: [BillKSmith] math function in a while loop [In reply to] Can't Post

I changed the selectall_arrayref and it worked!

Thanks a billion!


jnamiyo
New User

Jul 22, 2014, 9:25 AM

Post #5 of 5 (468 views)
Re: [BillKSmith] math function in a while loop [In reply to] Can't Post


Code
$total_price = sum  
map {$_->[0] * $_->[1]}
@{$dbh->selectall_arrayref($sql)};

$total_price_after = sum
map {$_->[1] * $_->[2]}
@{$dbh->selectall_arrayref($sql)};


And this gives me amount before the sale and the amount after the sale. Excellent, Thanks! You made me a hero!


(This post was edited by jnamiyo on Jul 22, 2014, 9:26 AM)

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives