0

I have a subroutine that generates the d-neighbors of an input sequence, which I was given help with here. My subroutine looks like:

#subroutine for generating d-neighbors
    sub generate_d_neighbors{
        # $sequence is the sequence to generate d-neighbors from
        my ($sequence) = @_;
        my @temp;
        my %returnHash;
        my @tempSeq = @$sequence;
        for(my $i = 0; $i <= 3; $i++){
            #print "-------------------\n";
            #reset back to original sequence
            @$sequence = @tempSeq;
            my @l = qw(A T G C); #list of possible bases
            my $baseToRemove = @$sequence[$i]; #get base from sequence at current index
            @temp = grep {$_ ne $baseToRemove} @l; #remove base

            for (my $j = 0; $j <= 2; $j++){         
                #replace sequence[i] with temp[j]
                @$sequence[$i] = $temp[$j];
                #add sequences to hash
                $returnHash{@$sequence} = $i;
            }
        }
        return %returnHash;
    }

I want to return a hash of the sequences. However, when I test it with

my @testSeq = ("A","T","C","G");
my %neighborhood = generate_d_neighbors(\@testSeq);
for my $neighbor (keys %neighborhood){
  print "key: $neighbor\t value: $neighborhood{$neighbor}\n";
}

I get an output of key:4 value:3

I would like the output to be the generated sequences as the keys (since they cannot have duplicates) , and the starting position in the sequence as the value. What am I doing wrong?

Community
  • 1
  • 1
Kyle Weise
  • 869
  • 1
  • 8
  • 29
  • 1
    The way you return the hash, the calling code, and the way you're printing it are all fine. If the output is not what you want, then the problem is in how you fill the hash. – melpomene Apr 24 '17 at 21:23
  • 1
    `@$sequence[$i]` isn't quite right, by the way. When you have an array `@foo`, the elements are accessed as `$foo[$i]` (unless you're taking a slice: `@foo[$i, $j, $k]`). So it should be `$$sequence[$i]` instead (which is normally written `$sequence->[$i]`). See `perldoc perlreftut`. – melpomene Apr 24 '17 at 21:25
  • 1
    `$returnHash{@$sequence}` makes no sense: The keys of a hash are strings, not arrays. You can create a string from your sequence: `$returnHash{join(" ", @$sequence)}` (this assumes your elements don't contain spaces). – melpomene Apr 24 '17 at 21:28
  • Awesome, this works. And thanks for the heads up in the previous comment. I noticed that went I print the hash it seems to be in a random order, is there a way to order it by value? – Kyle Weise Apr 24 '17 at 21:44
  • @KyleWeise Hashes are unordered by definition. You can, however, sort the keys in any order that you like. – Matt Jacob Apr 24 '17 at 22:32

0 Answers0