标题太恶心了,不知道该如何表达的清楚一点,英文叫Hash from two arrays。
我的意思是在Perl中,给了两个list,list含有相同个数的元素,如何将这两个list“合并”成一个hash,其中第一个list的元素为key,两一个list的元素为value。
还是挺恶心,看个例子吧:
1
my
@k
=
qw (a b c);
2 my @v = ( 1 , 2 , 3 );
3 # ...
4 # try to get a hash %h below;
5 %h = (
6 a => 1 ,
7 b => 2 ,
8 c => 3 ,
9 );
2 my @v = ( 1 , 2 , 3 );
3 # ...
4 # try to get a hash %h below;
5 %h = (
6 a => 1 ,
7 b => 2 ,
8 c => 3 ,
9 );
笨方法:
1
#
!/usr/bin/perl
2
3 use strict;
4 use warnings;
5
6 my @k = qw (a b c);
7 my @v = ( 1 , 2 , 3 );
8
9 my %h ;
11 for ( my $i = 0 ; i <= $ # k; i++) {
12 my $key = $k [ $i ];
13 my $value = $v [ $i ];
14 $h { $key } = $value ;
15 }
2
3 use strict;
4 use warnings;
5
6 my @k = qw (a b c);
7 my @v = ( 1 , 2 , 3 );
8
9 my %h ;
11 for ( my $i = 0 ; i <= $ # k; i++) {
12 my $key = $k [ $i ];
13 my $value = $v [ $i ];
14 $h { $key } = $value ;
15 }
简介的:
1
#
!/usr/bin/perl
2
3 use strict;
4 use warnings;
5
6 my @k = qw(a b c);
7 my @v = ( 1 , 2 , 3 );
8 my %h ;
9 @h { @k } = @v ;
2
3 use strict;
4 use warnings;
5
6 my @k = qw(a b c);
7 my @v = ( 1 , 2 , 3 );
8 my %h ;
9 @h { @k } = @v ;
再来一个简洁的:
1
#
!/usr/bin/perl
2
3 use strict;
4 use warnings;
5 use List :: MoreUtils qw(zip);
6
7 my @k = qw (a b c);
8 my @v = ( 1 , 2 , 3 );
9 my %hash = zip @keys , @vals ;
2
3 use strict;
4 use warnings;
5 use List :: MoreUtils qw(zip);
6
7 my @k = qw (a b c);
8 my @v = ( 1 , 2 , 3 );
9 my %hash = zip @keys , @vals ;