in reply to how to check which index $x is in an hash

If you use the lookup a lot then it's worth making a lookup table. Consider

use strict; use warnings; my %upload = (1 => 'one', 2 => 'two', 3 => 'three', 5 => 'five', 9 => +'nine', 10 => 'ten'); my @keys = sort {$a <=> $b} keys %upload; my %lookup = map { $keys[$_] => { prev => $_ ? $keys[$_ - 1] : undef, next => $_ != $#keys ? $keys[$_ + 1] : undef, } } 0 .. $#keys; for my $key (1, 5, 10) { if (defined $lookup{$key}{next}) { print "$lookup{$key}{next} follows $key\n"; } else { print "$key is the last item\n"; } if (defined $lookup{$key}{prev}) { print "$lookup{$key}{prev} precedes $key\n"; } else { print "$key is the first item\n"; } }

Prints:

2 follows 1 1 is the first item 9 follows 5 3 precedes 5 10 is the last item 9 precedes 10

The lookup creation is a little more succinct if you make use of autovivification:

my %lookup = map {$keys[$_] => {prev => $keys[$_ - 1], next => $keys[$ +_ + 1]}} 0 .. $#keys;

Update: see johngg's reply below!


DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^2: how to check which index $x is in an hash
by johngg (Canon) on May 21, 2007 at 22:13 UTC
    I think your more succinct version will have a problem with the first key. This is because $_ going into the map is going to be 0 thus prev => $keys[0 - 1] will result in prev => 10. At the other end, I think that next => $keys[$#keys + 1] will do the right thing as pointing off the end of the array should result in undef.

    Cheers,

    JohnGG

      Argh, you are quite right! I "checked" it, honest, I just didn't notice the line that says "10 precedes 1"!


      DWIM is Perl's answer to Gödel