Perl FIRSTKEY和NEXTKEY如何工作?

前端之家收集整理的这篇文章主要介绍了Perl FIRSTKEY和NEXTKEY如何工作?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Tie :: Hash有这些:
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函数返回散列中的项目数.对键的任何调用都会重置键和each使用的迭代器,因为它耗尽了迭代器.

对密钥的调用实际上是对FIRSTKEY的调用调用NEXTKEY,直到没有剩余的项目还没有返回.

对每个人的呼叫是对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}};
}
原文链接:https://www.f2er.com/Perl/241675.html

猜你在找的Perl相关文章