andybshaker has asked for the wisdom of the Perl Monks concerning the following question:

Hi everyone, I have the following chunk of code:

foreach $G (@array1){ for $x (0..$#array2){ if($array2[$x] =~ /$G/){ push(@Coordinates,"$array2[$x]"); } } }

I would expect this to create the array "Coordinates" with every value of array2 that matches array1, but what ends up happening is that the array only contains one value, the last value of array1--which indicates that it gets continuously replaced. How can I fix this?

Replies are listed 'Best First'.
Re: Why does every value of the array get replaced?
by toolic (Bishop) on May 27, 2015 at 17:50 UTC
    What exactly is in each array? This works:
    use warnings; #use strict; use Data::Dumper; my @array1 = 1..4; my @array2 = 2..6; foreach $G (@array1){ for $x (0..$#array2){ if($array2[$x] =~ /$G/){ push(@Coordinates,"$array2[$x]"); } } } print Dumper(\@Coordinates); __END__ $VAR1 = [ '2', '3', '4' ];

    See also the Basic debugging checklist

      foreach $G (@array1) { push @Coordinates, grep { /$G/ } @array2 }
      Dum Spiro Spero
Re: Why does every value of the array get replaced?
by GotToBTru (Prior) on May 27, 2015 at 18:37 UTC

    No values are being replaced. The insert isn't working like you expect. What are the contents of @array1 and @array2?

    Dum Spiro Spero

      array1 contains gene accession numbers of this format: X65a293846,X65a030294,X65a129385 array2 contains much more information that looks like this: 37483919..36271893 - 0 0 - X65a293846 - - DAR 42948502..38291239 - 0 0 - X65a030294 - - DAR Both arrays are read in from a file like this:

      my $file = "gene.txt"; open(FH, "< $file") or die "Can't open $file for read"; while(<FH>){ push(@array1, $_); } close(FH);

      The strange thing is that before this, I manually entered them into an array and it worked fine. Only now is it having problems.

        Sorry, your description of the second array is unintelligible. Use <c> tags. Better still, I would suggest using the debugger to inspect the arrays immediately prior to your logic to make sure they contain what you expect. I suspect toolic's tip about chomp is also relevant.

        Dum Spiro Spero