Slice of a hash of hashes

U

usenet

Kindly consider the following code which illustrates my question:

#!/usr/bin/perl
use strict; use warnings;
use Data::Dumper;

my %hash;

$hash{1}{'foo'} = 'one';
$hash{2}{'foo'} = 'two';
$hash{3}{'foo'} = 'three';

my @foos;
push @foos, $hash{$_}{'foo'} for keys %hash;

print Dumper \@foos;

__END__

As you can see, I have created an array containing the values of the
various "foo" keys within the hash. But that seems a bit kludgy. It
seems I ought to be able to do something similar to this (with
slicing):

my @foos = @hash{keys %hash}{'foo'};

But I can't seem to figure out how to implement this approach.

I would appreciate some not-so-kludgy pointers. Thanks!
 
U

Uri Guttman

u> $hash{1}{'foo'} = 'one';
u> $hash{2}{'foo'} = 'two';
u> $hash{3}{'foo'} = 'three';

u> push @foos, $hash{$_}{'foo'} for keys %hash;

u> As you can see, I have created an array containing the values of the
u> various "foo" keys within the hash. But that seems a bit kludgy. It
u> seems I ought to be able to do something similar to this (with
u> slicing):

u> my @foos = @hash{keys %hash}{'foo'};

u> But I can't seem to figure out how to implement this approach.

perl 5 can't slice any intermediate levels (hash or array) in a
structure. it can only slice a single ref value which will be at the
lowest level of your structure that you access. intermediate keys/index
values have to be single so they can lookup the next level down. perl6
has such midlevel slice capabilities.

but you can do better than your push code with map:

my @foos = map $_->{'foo'}, values %hash ;

if you want more levels than you can nest the maps or loop more. if you
need to do that often then wrap that code in subs to make it easier to
use.

uri
 
M

Mumia W.

Kindly consider the following code which illustrates my question:

#!/usr/bin/perl
use strict; use warnings;
use Data::Dumper;

my %hash;

$hash{1}{'foo'} = 'one';
$hash{2}{'foo'} = 'two';
$hash{3}{'foo'} = 'three';

my @foos;
push @foos, $hash{$_}{'foo'} for keys %hash;

print Dumper \@foos;

__END__

As you can see, I have created an array containing the values of the
various "foo" keys within the hash. But that seems a bit kludgy. It
seems I ought to be able to do something similar to this (with
slicing):

my @foos = @hash{keys %hash}{'foo'};

But I can't seem to figure out how to implement this approach.

I would appreciate some not-so-kludgy pointers. Thanks!

I don't consider your original code to be kludgy, but here:

my @foos = map $_->{foo}, values %hash;

UNTESTED CODE
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,967
Messages
2,570,148
Members
46,694
Latest member
LetaCadwal

Latest Threads

Top