CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Hash value printing... WITH ARRAYS *dun dun dun*

 



jaydstein
New User

Feb 6, 2012, 2:52 PM

Post #1 of 3 (646 views)
Hash value printing... WITH ARRAYS *dun dun dun* Can't Post

I'm relatively new to perl and I'm at the point where I don't 100% understand the nitty gritty of what I am doing (but I'm trying ;) ). I'm not getting expected behavior from my code. I have a hash that contains either a scalar or an array, and I need to print, line-by-line, each value contained in a hash.

Here's my code:

Code
my $primaryFeatures = { 
'foo', ('fool', 'food', 'foot'),
'bar', ('barricade'),
};

while (my ($key, $value) = each(%$primaryFeatures)){
print "($key, $value)\n";
}


Here's what I want:

(foo, fool)
(foo, food)
(foo, foot)
(bar, barricade)


But one of the items in the array value ('fool', 'food', 'foot') is being picked up and interpreted as a key instead of a value. Here is what I am getting:

(foo, fool)
**(food, foot)**
(bar, barricade)


I've looked into the 'values' function. I could make that work... but sifting through the the keys and values for only the values is a little messy. What is the best way to do this?


BillKSmith
Veteran

Feb 6, 2012, 3:42 PM

Post #2 of 3 (643 views)
Re: [jaydstein] Hash value printing... WITH ARRAYS *dun dun dun* [In reply to] Can't Post

Use a hash of arrays. Note: The second array has only one element.


Code
use strict; 
use warnings;
my $primaryFeatures
= { foo => [ 'fool', 'food', 'foot' ],
bar => ['barricade'],
};
while ( my ( $key, $hash_value ) = each(%$primaryFeatures) ) {
foreach my $array_element (@$hash_value) {
print "($key, $array_element)\n";
}
}

Good Luck,
Bill


jaydstein
New User

Feb 7, 2012, 4:06 PM

Post #3 of 3 (617 views)
Re: [BillKSmith] Hash value printing... WITH ARRAYS *dun dun dun* [In reply to] Can't Post

Thank you for your assistance. ;)

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives