In Perl, how do I create a hash whose keys come from a given array?

后端 未结 14 840
你的背包
你的背包 2021-01-29 19:53

Let\'s say I have an array, and I know I\'m going to be doing a lot of \"Does the array contain X?\" checks. The efficient way to do this is to turn that array into a hash, wher

14条回答
  •  萌比男神i
    2021-01-29 20:23

    #!/usr/bin/perl -w
    
    use strict;
    use Data::Dumper;
    
    my @a = qw(5 8 2 5 4 8 9);
    my @b = qw(7 6 5 4 3 2 1);
    my $h = {};
    
    @{$h}{@a} = @b;
    
    print Dumper($h);
    

    gives (note repeated keys get the value at the greatest position in the array - ie 8->2 and not 6)

    $VAR1 = {
              '8' => '2',
              '4' => '3',
              '9' => '1',
              '2' => '5',
              '5' => '4'
            };
    

提交回复
热议问题