FAQ
Hi gurus!

I'm need to create a new hash dynamically using an existing hashs data in the format of another hash for comparison purposes. Here are my two hashes:

%newhash = (
hygiene_products => {
quantity_3 => "50",
item_2 => "soap",
item_3 => "shampoo",
num_items => "3",
quantity_1 => "5",
quantity_2 => "1",
item_1 => "conditioner",
},
cleaning_products => {
num_items => "1",
quantity_1 => "20",
item_1 => "mops",
},
);

%oldhash = (
hygiene_products => {
conditioner => "5",
shampoo => "50",
soap => "1",
},
cleaning_products => {
"mops" => "20",
},
);

I need to get oldhash's data into a new hash in the format of newhash so I can compare them. Also, I cannot rely on the order, that is even though conditioner might be item_1 in newhash it might not be first in oldhash. So, I'm at the point where I know the item # that the "items" in oldhash should be. I just don't know how to take this and dynamically create a new hash based on it. Anyone know how I can do this? Also, if I am approaching this problem wrong will someone please let me know what the better way to compare the values would be.

Thanks!

/Mark

Search Discussions

  • Shawn at Dec 3, 2001 at 12:33 am
    This should get you in the right direction..

    use strict;
    my %oldhash = (
    'hygiene_products' => {
    'conditioner' => "5",
    'shampoo' => "50",
    'soap' => "1"},
    'cleaning_products' => {
    'mops' => "20"
    }
    );

    my %newhash;
    foreach(keys %oldhash) {
    my $item_count;
    foreach my $item(keys %{$oldhash{$_}}) {
    $item_count++;
    $newhash{$_}{"item_$item_count"}=$item;
    $newhash{$_}{"quantity_$item_count"}=$oldhash{$_}{$item};
    }
    $newhash{$_}{'num_items'}=$item_count;
    }

    foreach(sort keys %newhash) {
    print "Hash Set: $_\n";
    foreach my $item (sort keys %{$newhash{$_}}) {
    print " Name: $item Value: $newhash{$_}{$item}\n";
    }
    }

    Shawn

    ----- Original Message -----
    From: "Mark Hanson" <markhanson@starband.net>
    To: <beginners@perl.org>
    Sent: Sunday, December 02, 2001 5:42 PM
    Subject: Urgent! creating new hash from hash based on format of another hash


    %newhash = (
    hygiene_products => {
    quantity_3 => "50",
    item_2 => "soap",
    item_3 => "shampoo",
    num_items => "3",
    quantity_1 => "5",
    quantity_2 => "1",
    item_1 => "conditioner",
    },
    cleaning_products => {
    num_items => "1",
    quantity_1 => "20",
    item_1 => "mops",
    },
    );

    %oldhash = (
    hygiene_products => {
    conditioner => "5",
    shampoo => "50",
    soap => "1",
    },
    cleaning_products => {
    "mops" => "20",
    },
    );

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
groupbeginners @
categoriesperl
postedDec 2, '01 at 11:37p
activeDec 3, '01 at 12:33a
posts2
users2
websiteperl.org

2 users in discussion

Shawn: 1 post Mark Hanson: 1 post

People

Translate

site design / logo © 2022 Grokbase