2

是否可以在其中存储有关哈希的信息?我的意思是,没有以普通方式将信息添加到哈希中,这会影响键、值等。

事情是我正在将 twod_array 读入哈希,但想将顺序存储在原始数组中,而不影响如何遍历哈希等。

例如:

my @the_keys=keys %the_hash;

不应返回有关哈希顺序的信息。

有没有办法在哈希中存储元数据?

4

2 回答 2

4

You can store arbitrary metadata with the tie mechanism. Minimal example with a package storage that does not affect the standard hash interface:

package MetadataHash;
use Tie::Hash;
use base 'Tie::StdHash';
use Scalar::Util qw(refaddr);
our %INSERT_ORDER;
sub STORE {
    my ($h, $k, $v) = @_;
    $h->{$k} = $v;
    push @{ $INSERT_ORDER{refaddr $h} }, $k;
}
1;

package main;
tie my %h, 'MetadataHash';
%h = ( I => 1, n => 2, d => 3, e => 4 );
$h{x} = 5;
# %MetadataHash::INSERT_ORDER is (9042936 => ['I', 'n', 'd', 'e', 'x'])
print keys %h;
# 'enIxd'
于 2012-07-02T12:29:06.787 回答
2

好吧,我想总是可以使用Tie::Hash::Indexed :

use Tie::Hash::Indexed;

tie my %hash, 'Tie::Hash::Indexed';
%hash = ( I => 1, n => 2, d => 3, e => 4 );
$hash{x} = 5;

print keys %hash, "\n";    # prints 'Index'
print values %hash, "\n";  # prints '12345'
于 2012-07-02T11:18:11.080 回答