On 8/3/11 Wed  Aug 3, 2011  11:12 AM, "Marc" <sono...@fannullone.us>
scribbled:

> I'm trying to sort a shopping cart basket on the item numbers.  The basket is
> stored in a hash.  There is a hashref called  %{$main::global->{cart}}  that
> Data::Dumper prints out like so:
> 
> $VAR1 = {
>           '1' => '1 1 SL-8206      73.15     Label 8.25" x 6"  0.8 73.15 ',
>           '3' => '3 1 WR-9253      13.98     Label - 3" x 9"   0.5 13.98 ',
>           '2' => '2 1 APT-46V      96.43     4"x6" Label, hook   1.8 96.43 '
>         };
> 
> I would like to grab the item numbers, i.e. SL-8206, to sort the cart on.
> Could someone point me to something to read up on this?  What is the above
> actually?  It looks to me like a hash of hashes of arrays(?).

No. It is just a one-level hash. $VAR1 is a reference to that hash. If it
included any embedded arrays, you would see brackets ([]) in the output. If
there were any embedded hashes, you would see more than one level of braces
({}).

Here is a program that prints out the items in order of item numbers. The
key is to extract and compare the item numbers from the hash value (I
shortened the data lines somewhat to avoid line wrap):

#!/usr/local/bin/perl
use strict;
use warnings;

my $var = {
  '1' => '1 1 SL-8206 73.15 Label 8.25" x 6"  0.8 73.15',
  '3' => '3 1 WR-9253 13.98 Label - 3" x 9"   0.5 13.98',
  '2' => '2 1 APT-46V 96.43 4"x6" Label, hook 1.8 6.43 '
};

for my $item ( 
  sort { substr($var->{$a},4,7) cmp substr($var->{$b},4,7) }
  keys %$var ) 
{
    printf("  %3s  %s\n", $item, $var->{$item});
}

This can be made more efficient by extracting the keys only once in a method
known as the "Schwartzian transform".

<http://en.wikipedia.org/wiki/Schwartzian_transform>



-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to