in reply to This is a useless node
I just realized the question is useless.
I'm not sure why you think so, how to take a slice of a hash is a valid question, maybe you could explain what resolution you found for your question?
Anyway, there are several ways to make a (shallow) copy of a part of a hash, here are a few:
my %h is really big and I don't have enough RAM to make a copy of it
This makes the question interesting. It turns out that, at least on my machine with Perl 5.26, from the options above:
use warnings; use strict; use feature qw/say/; my %bighash; { my $sz = 1_000_000; my $v = 'aaaaaaaaaaaaaa'; $bighash{$v++} = int(rand($sz))+1 for 1..$sz; } my @keys = keys %bighash; delete $bighash{aaaaaaaaaaaaab}; my %slice; say `ps -orss $$`=~s/\s+/ /gr; #%slice = map { $_ => $bighash{$_} } @keys; #@slice{@keys} = @bighash{@keys}; #%slice = %bighash{@keys}; $slice{$_} = $bighash{$_} for @keys; die if defined $slice{aaaaaaaaaaaaab}; # verify the slice die unless $slice{aaaaaaaaaaaaaa}>0 && $slice{aaaaaaaaaaaaaa}==$bighash{aaaaaaaaaaaaaa}; say `ps -orss $$`=~s/\s+/ /gr;
I want to load the slice directly into a hashref
As it turns out, changing my %slice into my $slice and changing the syntaxes into the following doesn't really make a big difference:
On the other hand, if for example the values in your hash are huge, then perhaps a different approach is needed - for example, in your second hash you could store references to the values of the first hash. Or, you may not even need to create a second hash in the first place, perhaps simply keeping the list of keys around to select values from the first hash is enough.
|
---|