I love hash slices and use them frequently:
my %h;
@h{@keys}=@vals;
Works brilliantly! But 2 things have always vexed me.
First, is it possible to combine the 2 lines above into a single line of code? It would be nice to declare the hash and populate it all at once.
Second, is it possible to slice an existing anonymous hash... something like:
my $slice=$anonh->{@fields}
First question:
my %h = map { $keys[$_] => $vals[$_] } 0..$#keys;
or
use List::MoreUtils qw( mesh );
my %h = mesh @keys, @vals;
Second question:
If it's ...NAME...
for a hash, it's ...{ $href }...
for a hash ref, so
my @slice = @hash{@fields};
is
my @slice = @{ $anonh }{@fields};
The curlies are optional if the reference expression is a variable.
my @slice = @$anonh{@fields};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With