in reply to Updating arrays within hashes

Though this isn't your actual problem (and we're actually not given enough of a snippet to see your problem), there is an efficiency issue that can be improved upon. If @prevarray changes infrequently, why not turn it into the keys of a hash, so that you can do hash lookups instead of grep?

Your code snippet doesn't show where @prevarray comes from, but it's safe to assume based on your snippet that it's generated before your foreach loop. Since you are grepping once for each loop iteration, storing @prevarray as hash keys would eliminate the "loop within a loop" that a grep within a foreach loop creates.

As for your question; there's no way that the logic you've shown in your snippet (your if(){}else{} statement) could produce the results you're describing unless there's a problem with your references. I think it's more likely that your snippet isn't an exact cut-and-paste of the code that's giving you trouble.


Dave

Replies are listed 'Best First'.
Re^2: Updating arrays within hashes
by jonnyw83 (Initiate) on Feb 10, 2011 at 12:20 UTC

    thanks for the reply. Apologies if this isn't clear I tried to keep it concise as possible so not to overload with code. This wasn't directly from my code so will paste a larger part see if it makes sense. The code is admittidely very ugly but its doing a very specific job. The @sequences is a list of two strings separated by a tab defined earlier still in the programme. @searchmotif is a short list of things to search for. I don't think I need to split the $temp3[0] into an array can just pattern match it but thought I'd leave this as it was written to see if it is clearer The larger bit of code is:

    foreach my $line4 (@sequences) {my @temp3 = split ( '\t', $line4); my $counter = 0; my $paa = chop ($temp3[0]); my @fouraas = split ( '', $temp3[0]); if ($paa =~ /s/i ) {$pStotal++; foreach my $key (@searchmotif) {unless ( my @stemp = grep ( /$key/, @ +fouraas)){ push (@{$nsaminoacids{$key}},$temp3[1]);next;} #closes if +loop else { push (@{$saminoacids{$key}},$temp3[1]); next;} #closes if +loop } #close foreach loop } #closes if S loop elsif ($paa=~ /t/i ) {$pTtotal++; foreach my $key (@searchmotif) {if (my @ttemp = grep ( /$key/, @foura +as)){ push (@{$taminoacids{$key}},$temp3[1]); } #close +s if loop else { push (@{$ntaminoacid +s{$key}},$temp3[1]); } #close +s if loop } #close while loop } #closes if T loop elsif ($paa =~ /y/i ){$pYtotal++; foreach my $key (@searchmotif) {if (my @ytemp = grep ( /$key/, @foura +as)){ push (@{$yaminoacids{$key}},$temp3[1]); } #close +s if loop else { push (@{$nyaminoacids{$k +ey}},$temp3[1]); } #close +s if loop } #close while loop } #closes if Y loop else {push (@error, "$line4\tNot recognised p amino acid\n"); } } #closes foreach loop

    i really don't understand why its not only using one of the actions after the unless command. This whole section if almost affectively just 3 repeats of what I posted ealier.