hoelzro has asked for the wisdom of the Perl Monks concerning the following question:

Hello monks! I was curious about ties recently, so I looked up the docs and started reading. However, when reading about NEXTKEY, I was wondering how to create a tied hash that has undef as a key. Here's my experimental code:
# TestHash.pm use strict; use warnings; package TestHash; sub TIEHASH { return bless [], $_[0]; } sub FIRSTKEY { return undef; } sub NEXTKEY { my ($this, $last) = @_; return $last >= 10 ? undef : $last + 1; }
So when I call keys on a tied hash of this variety, it returns (), as expected. But if I wanted to, how would I return an undef value without ending the keys list?

Thanks, Rob

Replies are listed 'Best First'.
Re: Tying hashes with undef keys
by ysth (Canon) on Jul 09, 2007 at 01:43 UTC
    Don't have time to try it now, but based on the perl source, returning an overloaded object should work.

    It also looks like NEXTKEY gets passed the previous key - something I don't remember seeing in the doc. Ah, it is documented. Learning something new every day++.

Re: Tying hashes with undef keys
by wind (Priest) on Jul 09, 2007 at 04:19 UTC
    Read perltie#Tying hashes

    I have not spent much time working with tied variables. However, it appears that the FIRSTKEY and NEXTKEY functions are supposed to return a key, value pair. The end of the list would therefore be denoted by (). Although your undef appears to work as well.

    Note that normally hash keys are as a rule defined strings. However, I would guess that you might be able to return an undefined key using the following
    sub FIRSTKEY { return (undef, 'foobar'); }
    - Miller