How do I initialize values in a hash without a loop?

前端 未结 4 576
夕颜
夕颜 2021-02-05 10:37

I am trying to figure out a way to initialize a hash without having to go through a loop. I was hoping to use slices for that, but it doesn\'t seem to produce the expected resul

4条回答
  •  無奈伤痛
    2021-02-05 11:24

    So, what you want is to populate the hash using an array for the keys, and an array for the values. Then do the following:

    #!/usr/bin/perl
    use strict;
    use warnings;
    
    use Data::Dumper; 
    
    my %hash; 
    
    my @keys   = ("a","b"); 
    my @values = ("1","2");
    
    @hash{@keys} = @values;
    
    print Dumper(\%hash);'
    

    gives:

    $VAR1 = {
              'a' => '1',
              'b' => '2'
            };
    

提交回复
热议问题