in reply to Multiple Key Problem help

while (<$fh>) {
   my ($key, $pos) = split /\s+/;
   $positions{$key} = $pos;
}

Needs to be replaced with:
while (<$fh>) {
   chomp; #line added
   my ($key, $pos) = split /\s+/;
   if (!$positions{$key}) {
     $positions{$key} = $pos;
   } else {
     my $ref = $positions{$key};
     push @$ref,$pos;
   }
}
and also replace: for my $key ( sort keys %positions ) {
   .......
}

with:

for my $key ( sort keys %positions ) {
   my $ref = $positions{$key};
   foreach my $value (@$ref) {
     .......
   }
}
As the key can hold multiple values the hash contains an array

Replies are listed 'Best First'.
Re^2: Multiple Key Problem help
by ashnator (Sexton) on Dec 23, 2008 at 15:57 UTC
    I modified my code with ur very kind feed back but I am
    getting an error like this now :-
    Can't use string("72")as an array reference while "strict refs" in use + at test.pl line 21, <$fh> line 2
    My updated code is:-
    #!/usr/bin/perl use strict; use warnings; my $qfn1 = "wah.txt"; my $qfn2 = "taj.txt"; my %positions; { open(my $fh, '<', $qfn1) or die("Cannot open file \"$qfn1\": $!\n"); while (<$fh>) { chomp; my ($key, $pos) = split /\s+/; if (!$positions{$key}) { $positions{$key} = $pos; } else { my $ref = $positions{$key}; push @$ref,$pos; } } } my %sequences; { open(my $fh, '<', $qfn2) or die("Cannot open file \"$qfn2\": $!\n"); my $key; while (<$fh>) { if ( s/^>// ) { $key = ( split /\|/ )[1]; } else { chomp; $sequences{$key} .= $_; } } } for my $key ( sort keys %positions ) { my $ref = $positions{$key}; foreach my $value (@$ref) { if ( ! exists( $sequences{$key} )) { warn "KEY $key in File1 not found in File2\n"; next; } if ( length( $sequences{$key} ) < $positions{$key} ) { warn "KEY $key: File2 string length too short for File1 positi +on value\n"; next; } my $index = rindex( $sequences{$key}, "ATG", $positions{$key} ); if ( $index < 0 ) { warn sprintf( "KEY %s: No ATG in File2 string prior to positio +n %d\n", $key, $positions{$key} ); next; } $index += 3 while ( ($index + 3) < $positions{$key} ); print "$key $positions{$key} " . substr($sequences{$key}, $index, +3) . "\n"; } }
      There was a formatting error in u671296's code. The line $positions{$key} = $pos; should read $positions{$key} = [$pos];, in order to create an array reference. Then the push in the else branch will have an array reference to push into, rather than just a scalar number.
        I wonder why the square brackets disappeared ? Perhaps because I possibly didn't put the code in a c tag ?
      A reply falls below the community's threshold of quality. You may see it by logging in.