领带::哈希有这些:

sub FIRSTKEY { my $a = scalar keys %{$_[0]}; each %{$_[0]} }
sub NEXTKEY  { each %{$_[0]} }

NEXTKEY接受两个参数,其中一个是最后一个键,但是arg从未被引用?

除了perltie之外,各种Tie文档都没有对此有所说明:
my $a = keys %{$self->{LIST}};      # reset each() iterator

查看每个文档并不会增加此功能。

这是怎么回事?

最佳答案

如果您关心最后访问哪个键,则只需担心NEXTKEY的第二个参数。默认情况下,哈希值不关心顺序,因此不使用它。

至于第二部分,标量上下文中的 keys 函数返回哈希中的项目数。对键的任何调用都会重置keys each 使用的迭代器,因为它会耗尽迭代器。

keys的调用实际上是对FIRSTKEY的调用,并且实际上是对NEXTKEY的调用,直到没有剩余的未归还的项目为止。

each的调用是对FIRSTKEY的调用(如果尚未调用FIRSTKEY)或对NEXTKEY的调用(如果已调用FIRSTKEY)。

#!/usr/bin/perl

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";
}

package HASH::Sorted;

sub TIEHASH {
    my $class = shift;

    return bless { _hash => { @_ } }, $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;

    #build iterator
    $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}};
}

10-01 18:23