in reply to Finding Previous and Next in a HASH

my %nxt; my %prev; my $prv; for (sort { $a <=> $b } keys %hash) { if (defined $prv) { $nxt{$prv} = $_; $prev{$_} = $prv; } $prv = $_; }

Replies are listed 'Best First'.
Re: Re: Finding Previous and Next in a HASH
by turnstep (Parson) on Dec 12, 2000 at 07:31 UTC
    This is a good answer, but it fails to point the first element "back" to the last, and the last "forward" to the first. Here's one way to do that:
    
    my %nxt;
    my %prev;
    
    my $prv;
    my $first;
    for (sort { $a <=> $b } keys %hash) {
      $first ||= $_;
      if (defined $prv) {
        $nxt{$prv} = $_;
        $prev{$_} = $prv;
      }
      $prv = $_;
    }
    
    $nxt{$prv}=$first;
    $prev{$first}=$prv;