有谁知道如何使用作为perl键的字符串对的散列?配对作为散列键
喜欢的东西...
{
($key1, $key2) => $value1;
($key1, $key3) => $value2;
($key2, $key3) => $value3;
等....
有谁知道如何使用作为perl键的字符串对的散列?配对作为散列键
喜欢的东西...
{
($key1, $key2) => $value1;
($key1, $key3) => $value2;
($key2, $key3) => $value3;
等....
的ASCII单位分离你不能有一对标量的哈希键,但你可以做一个多哈希:
my %hash;
$hash{$key1}{$key2} = $value1;
$hash{$key1}{$key3} = $value2;
$hash{$key2}{$key3} = $value3;
如果你想一次定义这一切:或者
my %hash = ($key1 => { $key2 => $value1, $key3 => $value2 },
$key2 => { $key3 => $value3 });
,它是否适合你的情况,你可以只串连你的钥匙š一起
$hash{$key1 . $key2} = $value1; # etc
或者添加一个定界符在键分离:
$hash{"$key1:$key2"} = $value1; # etc
我这样做:
{ "$key1\x1F$key2" => $value, ... }
有一个辅助方法
一般:
sub getKey() {
return join("\x1F", @_);
}
{ getKey($key1, $key2) => $value, ... }
--- - 编辑-----
更新上面的代码使用每recommendation from @chepner above
用法:多个键在哈希一个单个值的可用于实现2D矩阵或N维矩阵!
#!/usr/bin/perl -w
use warnings;
use strict;
use Data::Dumper;
my %hash =();
my ($a, $b, $c) = (2,3,4);
$hash{"$a, $b ,$c"} = 1;
$hash{"$b, $c ,$a"} = 1;
foreach(keys(%hash))
{
my @a = split(/,/, $_);
print Dumper(@a);
}
你可以使用一个invisible separator加入坐标:
主要用于数学,无形分离器(
U+2063
)提供的字符之间的分隔体,其中标点符号或空间可以在两可省略如三维索引像ij
。
#!/usr/bin/env perl
use utf8;
use v5.12;
use strict;
use warnings;
use warnings qw(FATAL utf8);
use open qw(:std :utf8);
use charnames qw(:full :short);
use YAML;
my %sparse_matrix = (
mk_key(34,56) => -1,
mk_key(1200,11) => 1,
);
print Dump \%sparse_matrix;
sub mk_key { join("\N{INVISIBLE SEPARATOR}", @_) }
sub mk_vec { map [split "\N{INVISIBLE SEPARATOR}"], @_ }
~/tmp> perl mm.pl |xxd 0000000: 2d2d 2d0a 3132 3030 e281 a331 313a 2031 ---.1200...11: 1 0000010: 0a33 34e2 81a3 3536 3a20 2d31 0a .34...56: -1.
使用$;隐式(或显式)中的散列键,用于多维仿真,就像这样:
my %hash;
$hash{$key1, $key2} = $value; # or %hash = ($key1.$;.$key2 => $value);
print $hash{$key1, $key2} # returns $value
你甚至可以设置$;到\ x1F的如果需要的话(默认为\ 034,从在AWK SUBSEP):
local $; = "\x1F";
相关:[哈希::多键(http://p3rl.org/Hash::MultiKey)[领带:: RefHash](http://p3rl.org/Tie::RefHash)[Perl可以将数组引用存储为散列键吗?](http:// stackoverflow。com/questions/3083433/can-perl-store-an-array-reference-as-a-hash-key)[如何使用'子例程引用'作为散列键](http://stackoverflow.com/questions/10795386 /如何使用子例程引用作为散列键) – daxim 2013-03-11 09:36:00