Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous Hash Slices - syntax?

Tags:

perl

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}
like image 739
mswanberg Avatar asked Jul 24 '13 14:07

mswanberg


1 Answers

  • 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};
    
    • Mini-Tutorial: Dereferencing Syntax
    • References quick reference
    • perlref
    • perlreftut
    • perldsc
    • perllol
like image 125
ikegami Avatar answered Oct 01 '22 03:10

ikegami