Front page | perl.beginners |
Postings from March 2002
Re: If statement
Thread Previous
From:
Chas Owens
Date:
March 29, 2002 09:43
Subject:
Re: If statement
Message ID:
1017423577.26201.50.camel@tert.icallinc.com
On Fri, 2002-03-29 at 11:46, Ned Cunningham wrote:
> HI,
> I am having a very newbie problem.
> I am reading an Access database with ODBC and have my data read into
>
> $Data{STATE}
>
> My problem is now I need to match to 16 different states.
>
>
>
> I have so far
>
> If ( $Data{STATE} eq "MA" )
>
> Process data
>
>
> My question is should I use an array to test against and how to code it?
>
> ??-
> @state="MA CI DE IN OH";
>
> Thank you for anyhelp
What you want is a hash of coderefs:
<example>
my %state = (
MA => sub {
print "In Maryland the sales tax is 4.5%\n";
return shift * 1.045;
},
OH => sub {
print "In Ohio the sales tax is 3%\n";
return shift * 1.03;
},
GL => sub {
print "In Gonawana Land the sales tax is ",
"the square root of the price or ten ",
"dollars, whichever is smaller\n";
my $price = shift;
my $tax = sqrt($price);
$tax = 10 if $tax > 10;
return $price + $tax;
}
);
$sth = $dbh->prepare("select * from transactions");
$sth->execute;
while (my $trans = $sth->fetchrow_hashref) {
my $cost = ($state{$trans->{STATE}})($trans->{PRICE});
print "Customer $trans->{CUST_NAME} owes $cost dollars\n";
}
$sth->finish;
</example>
Of course I don't know what you want to do, I just assumed sales tax
because that is something different in between states in the US. NOTE:
This example (except for GL, which required actual code, which is why I
included it) could have been much easier to code like this:
my %sales_tax = (
MA => 1.045,
OH => 1.03,
);
<snip />
my $cost = $trans->{PRICE} * $sales_tax{$trans->{STATE}};
<snip />
--
Today is Pungenday the 15th day of Discord in the YOLD 3168
All Hail Discordia!
Missile Address: 33:48:3.521N 84:23:34.786W
Thread Previous