in reply to finding neighbors of an element in arrays

I'm not sure what you are trying to do, but there are a number of obvious errors in your code.

  1. $element=$_; most likely sets $element to undef - $_ does not contain whatever you think it does
  2. $element used in foreach $element is not the same $element used in print " $h{$element}";. The value used with the hash is most likely undef.
  3. $h{$element}=$domains1[$i+1]; replaces the value from the $h{$element}=$domains1[$i-1]; assignment.

If resolving the errors pointed out above doesn't fix your problem then you should show us a small sample of your input data and the output you expect from it. Maybe though you want to achieve something like:

use strict; use warnings; my $list = <<LIST; PF10417.3 PF11001.3 PF05.3 LIST my @domains1 = ('PF05.3', 'PF11001.3', 'PF00389.24', 'PF10417.3'); my @domains2 = ('PF01', 'PF02', 'PF11001.3', 'PF00389'); my @domains3 = ('PF00389.24', 'PF05.3', 'PF01', 'PF00389'); my %neighbours; for my $domain (\@domains1, \@domains2, \@domains3) { for my $idx (0 .. $#$domain) { my @near = grep {$_ >= 0 && $_ <= $#$domain} $idx - 1, $idx + +1; push @{$neighbours{$domain->[$idx]}}, map {$domain->[$_]} @nea +r; } } open my $inList, '<', \$list or die "cannot open 'domainlist'becuase:$ +!"; while (defined (my $domain = <$inList>)) { chomp $domain; print "Domain $domain has neighbours: @{$neighbours{$domain}}\n"; }

Prints:

Domain PF10417.3 has neighbours: PF00389.24 Domain PF11001.3 has neighbours: PF05.3 PF00389.24 PF02 PF00389 Domain PF05.3 has neighbours: PF11001.3 PF00389.24 PF01
True laziness is hard work

Replies are listed 'Best First'.
Re^2: finding neighbors of an element in arrays
by Anonymous Monk on Jul 28, 2011 at 13:14 UTC

    thank you so much.it was great.but please give me some explanation about these lines of code.thank you again.

    for my $idx (0 .. $#$domain) { my @near = grep {$_ >= 0 && $_ <= $#$domain} $idx - 1, $idx + +1; push @{$neighbours{$domain->[$idx]}}, map {$domain->[$_]} @nea +r; } }

      The loop iterates over all the element indexes in the current domain array. For each index it generates a list containing the index before and after the current index: $idx - 1, $idx + 1. The grep then filters the list to give a list containing just valid indexes (it removes -1 or scalar @$domain values if present).

      That leaves the neighbour indexes for the current index in @near. The map turns the neighbour indexes into a list of neighbour values. The push pushes the list into the array referenced by the hash entry for the value at the current index.

      Looking back over that description I'm glad to be using Perl rather than COBOL!

      True laziness is hard work