这个方法使用自定义的 each 方法,允许您对排序后的哈希表进行多次迭代。但是,所有关于不允许添加或删除键的标准规则仍然有效。在调用 STORE
或 DELETE
时,很容易添加一个警告,提示迭代器仍在使用中。
use strict;
use warnings;
my $i = 0;
tie my %h, "HASH::Sorted", map { $_ => $i++ } "a" .. "g";
for my $key (keys %h) {
print "$key => $h{$key}\n";
}
print "\n";
my $first = each %h;
print "first $first => $h{$first}\n";
my ($second_key, $second_value) = each %h;
print "second $second_key => $second_value\n";
print "\nall of them again:\n";
for my $key (keys %h) {
print "$key => $h{$key}\n";
}
print "\nmultiple iterators\n";
my $o = tied %h;
while (my ($k, $v) = $o->each("outer")) {
print "$k => $v\n";
while (my ($k, $v) = $o->each("inner")) {
print "\t$k => $v\n";
}
}
print "\nhybrid solution\n";
while (my ($k, $v) = each %h) {
print "$k => $v\n";
while (my ($k, $v) = $o->each) {
print "\t$k => $v\n";
}
}
package HASH::Sorted;
sub each {
my ($self, $iter_name) = (@_, "DEFAULT");
unless (exists $self->{_iters}{$iter_name}) {
$self->{_iters}{$iter_name} = [ sort keys %{$self->{_hash}} ];
}
unless (@{$self->{_iters}{$iter_name}}) {
delete $self->{_iters}{$iter_name};
return;
}
my $key = shift @{$self->{_iters}{$iter_name}};
if (wantarray) {
return $key, $self->{_hash}{$key};
}
return $key;
}
sub TIEHASH {
my $class = shift;
return bless {
_hash => { @_ },
_iters => {},
}, $class;
}
sub FETCH {
my ($self, $key) = @_;
return $self->{_hash}{$key};
}
sub STORE {
my ($self, $key, $value) = @_;
return $self->{_hash}{$key} = $value;
}
sub DELETE {
my ($self, $key) = @_;
return delete $self->{_hash}{$key};
}
sub CLEAR {
my $self = shift;
%{$self->{_hash}} = ();
}
sub EXISTS {
my ($self, $key) = @_;
return exists $self->{_hash}{$key};
}
sub FIRSTKEY {
my $self = shift;
$self->{_list} = [ sort keys %{$self->{_hash}} ];
return $self->NEXTKEY;
}
sub NEXTKEY {
my $self = shift;
return shift @{$self->{_list}};
}
sub SCALAR {
my $self = shift;
return scalar %{$self->{_hash}};
}
my ($k, $v) = each %h;
将以列表上下文调用FIRSTKEY
和NEXTKEY
,实际上它将调用FETCH
来获取值。 我会修改代码的。 - Chas. Owens