package SortedHash; use strict; use warnings; use Carp; our $debug = 0; sub TIEHASH { my $class = shift; my $obj = { hash => {}, keys => [], index => 0 }; bless $obj, $class; } sub FETCH { my $this = shift; carp "FETCH called with: @_" if $debug; my ($key) = @_; return $this->{hash}{$key}; } sub STORE { my $this = shift; carp "STORE called with: @_" if $debug; my ($key, $val) = @_; $this->{hash}{$key} = $val; @{$this->{keys}} = sort (keys %{$this->{hash}}); return $val; } sub DELETE { my $this = shift; carp "DELETE called with: @_" if $debug; my ($key) = @_; if (exists $this->{hash}{$key}){ delete $this->{hash}{$key}; @{$this->{keys}} = sort keys %{$this->{hash}}; return 1; } else { return 0; } } sub FIRSTKEY { my $this = shift; carp "FIRSTKEY called with: @_" if $debug; $this->{index} = 0; return $this->{keys}[$this->{index}++]; } sub NEXTKEY { my $this = shift; carp "NEXTKEY called with: @_" if $debug; if ($this->{index} == @{$this->{keys}}){ $this->{index} = 0; return undef; } else { return $this->{keys}[$this->{index}++]; } } sub EXISTS { my $this = shift; carp "EXISTS called with: @_" if $debug; my ($key) = @_; return exists $this->{hash}{$key}; } sub CLEAR { my $this = shift; carp "CLEAR called with: @_" if $debug; %{$this->{hash}} = (); @{$this->{keys}} = (); $this->{index} = 0; } sub SCALAR { my $this = shift; carp "SCALAR called with: @_" if $debug; croak "Hashes tied to the ", tied($this), " class cannot be used in scalar context"; } sub UNTIE { my $this = shift; carp "UNTIE called with: @_" if $debug; } sub DESTROY { my $this = shift; carp "DESTROY called with: @_" if $debug; } 1;