David Gilden wrote:
Thanks Dan and the rest of the list for helping hone my PERL skills.
Below is the data structure I am using, I think it is a HoH -- Hash of Hash Did get that right ? :)
Yes.
# This is the data structure
%bags_ordered = ( "bag-style-fur" => { price => 10, image_name => 'FIO-142b-small', quantity=> 2 },
"bag-style-leather" => { price => 12, image_name => 'GUC-208-small', quantity=> 5, },
);
....
What I was looking for was way to initialize the %bags_ordered and remove the 'unless exists'. Does this test do something that I am not seeing or understanding like prevent two 'keys' with different values?
The below code does not do that, but that is what the 'exists' is designed to do, and is something you should do for completeness.
%bags_ordered =(); # ok
This clears all values from the hash. When you assign a hash it always takes an even number of elements, this is a 'list'. There is an FAQ about the difference between lists and arrays.
%bags_ordered = {}; # not ok -- Reference found where even-sized list expected
This is not ok, because you are trying to assign a single scalar (aka an empty anonymous hash (reference)) to a variable that expects an even numbered list assignment. You either must assign like so:
%bags_ordered = ('key',{});
or
%bags_ordered = %{}; (probably works but is the same as the first example above, and rather silly ;-)).
or
$bags_ordered{'key'] = {};
which assigns an empty anonymous hash as the value of key 'key' in the hash.
......
@bags = param('handbag'); #CGI.pm
##
foreach my $bag (@bags){
$bags_ordered{$bag} = {} unless exists $bags_ordered{$bag}; }
##
So this will assign an empty anonymous hash to the key that is set in $bag if that key didn't already exist. Which is possibly what you want to do.
# Is the code below -- better or correct?
foreach my $bag (@bags){
$bags_ordered{$bag} = $bag unless exists $bags_ordered{$bag} }
This will assign a regular scalar (the value of $bag) to the key that is set in $bag if that key didn't already exist. This is probably not what you want to do in your case, as it appears you are trying to build a list of items, and with each item it has certain properties. The above will set something like:
$bags_ordered{'handbag'} = 'handbag';
Which then when you retrieve a value from the hash (%bags_ordered) you would have to check to see if it is a hashref or a scalar...
You might also want to keep your structure normalized, which is somewhat what you have done by assigning the {} to the key...but you might want to go ahead and populate the keys of *that* hash also, then you are guaranteed to have a "normal" structure. Like so:
$bags_ordered{$bag} = {'price'=>0,'image_name'=>'spacer.gif','quantity'=>0};
But again we are delving into design decisions, and how you are going to then be using your data structure later.....
Hope this isn't to confusing.
http://danconia.org
-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]