Well, first of all you have to change ALL of your code that uses this cart structure -- not just this one sub -- if you want to switch the cart from a hash to an array. I actually think this is probably the wrong approach and you would be better off making unique item ids for every one of your colors. You could also cheat by making a generated key to use in your shopping cart: my $item_key = $item_id . '|' . $color or something like that.

Just to give you an idea of what you need to do to that code to change it to arrays, here is another take on your add_item sub:

sub add_item { my ($dbh, $cart_ref, $item_id, $qty, $color) = @_; # If the item isn't already in the cart, look it up from the datab +ase # and store it in the cart as a new entry with a quantity of zero. my $saw_item = 0; foreach my $item (@{$cart_ref}) { if (($item->{'id'} == $item_id) && $item->{'color'} eq $color) +) { $saw_item = 1; break; } } if (!$saw_item) { my $sth = $dbh->prepare ("SELECT item_id, description, categor +y, price, picture, thumbnail, mime_type, color FROM catalog_pet WHERE + item_id = ?"); $sth->execute ($item_id); my $row = $sth->fetchrow_hashref (); return if !defined ($row); # this shouldn't happen... my $item_ref = {}; $item_ref->{description} = $row->{description}; $item_ref->{price} = $row->{price}; $item_ref->{qty} = 1; $item_ref->{color} = $color; } $item_ref->{qty} = $qty; push (@{$cart_ref}, @item_ref); }
Note that it is no longer possible to look up a single item in the cart by ID with this structure: you have to loop through all the items.

In reply to Re: Re: Re: Need duplicate item entries in shopping cart by perrin
in thread Need duplicate item entries in shopping cart by b310

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.