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: Re: [g4143] Trouble accessing Hash of Arrays: Edit Log



Zhris
Enthusiast

Apr 7, 2013, 5:18 PM


Views: 624
Re: [g4143] Trouble accessing Hash of Arrays

Hi g4142,

FYI,

You can determine the subscript of the last element of the array directly:


Code
(@{$sampleHash{$_}} - 1) 
$#{$sampleHash{$_}}


Also in your second foreach; 1) looping / accessing via subscript is unnecessary 2) you could have made use of previously assigned $h in the condition.

Here are my simplified versions:


Code
# without sorting: 
foreach my $list (values %sampleHash)
{
print "$_\n" foreach (@$list);
}


# without sorting while:
while (my ($unused_key, $list) = each (%sampleHash))
{
print "$_\n" foreach (@$list);
}


# with sorting:
foreach my $key (sort keys %sampleHash)
{
print "$_\n" foreach (@{$sampleHash{$key}});
}


In fact, if we want to make them more compact:


Code
$" = "\n"; # unlocalised list separator assignment 


# without sorting:
print "@$_\n" for (values %sampleHash);


# with sorting:
print "@$_\n" for (map { $sampleHash{$_} } sort keys %sampleHash);


Regards,

Chris


(This post was edited by Zhris on Apr 7, 2013, 6:12 PM)


Edit Log:
Post edited by Zhris (Enthusiast) on Apr 7, 2013, 5:19 PM
Post edited by Zhris (Enthusiast) on Apr 7, 2013, 5:20 PM
Post edited by Zhris (Enthusiast) on Apr 7, 2013, 5:21 PM
Post edited by Zhris (Enthusiast) on Apr 7, 2013, 5:24 PM
Post edited by Zhris (Enthusiast) on Apr 7, 2013, 5:33 PM
Post edited by Zhris (Enthusiast) on Apr 7, 2013, 5:34 PM
Post edited by Zhris (Enthusiast) on Apr 7, 2013, 5:34 PM
Post edited by Zhris (Enthusiast) on Apr 7, 2013, 5:35 PM
Post edited by Zhris (Enthusiast) on Apr 7, 2013, 5:38 PM
Post edited by Zhris (Enthusiast) on Apr 7, 2013, 5:40 PM
Post edited by Zhris (Enthusiast) on Apr 7, 2013, 5:40 PM
Post edited by Zhris (Enthusiast) on Apr 7, 2013, 5:41 PM
Post edited by Zhris (Enthusiast) on Apr 7, 2013, 5:42 PM
Post edited by Zhris (Enthusiast) on Apr 7, 2013, 5:45 PM
Post edited by Zhris (Enthusiast) on Apr 7, 2013, 5:53 PM
Post edited by Zhris (Enthusiast) on Apr 7, 2013, 5:53 PM
Post edited by Zhris (Enthusiast) on Apr 7, 2013, 5:54 PM
Post edited by Zhris (Enthusiast) on Apr 7, 2013, 6:05 PM
Post edited by Zhris (Enthusiast) on Apr 7, 2013, 6:07 PM
Post edited by Zhris (Enthusiast) on Apr 7, 2013, 6:09 PM
Post edited by Zhris (Enthusiast) on Apr 7, 2013, 6:09 PM
Post edited by Zhris (Enthusiast) on Apr 7, 2013, 6:10 PM
Post edited by Zhris (Enthusiast) on Apr 7, 2013, 6:11 PM
Post edited by Zhris (Enthusiast) on Apr 7, 2013, 6:12 PM


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

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