Gossamer Forum
Home : General : Perl Programming :

how to check if the array is empty???

Quote Reply
how to check if the array is empty???
  


if ( $cart ) { non empty }
else { empty cart }


basicly this should work. while i have difficult in doing in right in the below code

in sub display_cart

# getting the cart's contents
my $cart = $session->param("CART") || [ ];

if ( $cart ) { non empty }
else { empty cart }

it seems no mather cart is empty or not. $cart alway has an value there. what is the problem ?
or how to fix the code to make it workable?

Thanks
Quote Reply
Re: [courierb] how to check if the array is empty??? In reply to
  


if ( $cart ) { non empty }
else { empty cart }

use CGI::Session;
my $cgi = new CGI;
my $session = new CGI::Session(undef, $cgi, {Directory=>'F:/tmp'});
print $session->header();

# $cookie = $cgi->cookie(CGISESSID => $session->id );
# print $cgi->header(-cookie=>$cookie);
# Imaginary database in the form of a hash
%products = (
1001 => [ "usr/bin/perl t-shirt", 14.99],
1002 => [ "just perl t-shirt", 14.99],
1003 => [ "shebang hat", 15.99],
1004 => [ "linux mug", 19.99],
# on and on it goes....
);
# getting the run mode for the state. If doesn't exist,
# defaults to "display", which shows the cart's content
$cmd = $cgi->param("cmd") || "display";
if ( $cmd eq "display" ) {
print display_cart($cgi, $session);
} elsif ( $cmd eq "add" ) {
print add_item($cgi, $session, \%products,);
} elsif ( $cmd eq "remove") {
print remove_item($cgi, $session);
} elsif ( $cmd eq "clear" ) {
print clear_cart($cgi, $session);
} else {
print display_cart($cgi, $session);
}

sub add_item {
my ($cgi, $session, $products) = @_;
# getting the itemID to be put into the cart
my $itemID = $cgi->param("itemID") or die "No item specified";
# getting the current cart's contents:
my $cart = $session->param("CART") || [];
# adding the selected item
push @{ $cart }, {
itemID => $itemID,
name => $products->{$itemID}->[0],
price => $products->{$itemID}->[1],
};
# now store the updated cart back into the session
$session->param( "CART", $cart );
# show the contents of the cart
return display_cart($cgi, $session);
}


sub display_cart {
my ($cgi, $session) = @_;
# getting the cart's contents
my $cart = $session->param("CART") || [];
my $total_price = 0;
my $RV = q~<table><tr><th>Title</th><th>Price</th></tr>~;
if ( $cart ) {
for my $product ( @{$cart} ) {
$total_price += $product->{price};
$RV = qq~
<tr>
<td>$product->{name}</td>
<td>$product->{price}</td>
</tr>~;
}
} else {
$RV = qq~
<tr>
<td colspan="2">There are no items in your cart
yet</td>
</tr>~;
}
$RV = qq~
<tr>
<td><b>Total Price:</b></td>
<td><b>$total_price></b></td>
</tr></table>~;
return $RV;
}

sub clear_cart {
my ($cgi, $session) = @_;
$session->clear(["CART"]);
}
Quote Reply
Re: [courierb] how to check if the array is empty??? In reply to
  

sorry.
it is ok now by the substition below

if ( @{$cart} )