in reply to comparing strings

It might be easier for you to use just strings rather than the overhead of arrays for this. Use the substr function to get the nth character in the sequence.
my $dna1 = 'CACTATGAGTGATCGC'; my $dna2 = 'ACTGACTAATGCGTTG'; print "$dna1\n$dna2\n"; for (0 .. length($dna1)-1) { if (substr($dna1,$_,1) eq substr($dna2,$_,1)) { print ' '; } else { print '*'; } } print "\n"; __END__ # prints this: CACTATGAGTGATCGC ACTGACTAATGCGTTG **** ** * *****
Also, there are quite a few problems in your original code. First, the value that you want to loop/iterate over is the number N when you are looking at the Nth character. But the foreach loop will set $base to each of the values in @lines1 and then to all the values in @lines2. You cannot get a pair of elements from two different arrays using a foreach loop. Also note that inside the loop, you are comparing the first elements of the array each time. You want to compare a different pair of elements each time through the loop. Lastly, @lines1[0] is invalid (at least until Perl6), and what you need to say instead is $lines1[0].

HTH and keep trying!

blokhead

Replies are listed 'Best First'.
Re: Re: comparing strings
by Anonymous Monk on Oct 30, 2002 at 16:26 UTC
    Thanks blokhead, But I am still having a few problems... I incorporated the snippet you gave me which works fine apart from it doesn't print the correct no. of *'s to correspond to the number of mismatches! This is what i did its slightly different from yours.
    for ($dna_counter = 0; $dna_counter < $length_dna ; $dna_counter++ ) { if (substr(@lines, $_, 1) eq substr (@lines2, $_, 1)) { print ''; } else { print "*"; } } print "\n";
      Of course, if you're using arrays, you just need
      if ($lines{$_] eq $lines2[$_]) {
      The following will replace the non-matching chars in the string  $str1 with "*" (and leave the matching chars) by converting $str2 to a regex:
      $str2 =~ s/./(?:($&)|.)/g; print map{$_||'*'} $str1 =~ /$str2/


        p
      This is what i did its slightly different from yours.
      ... if (substr(@lines, $_, 1) eq substr (@lines2, $_, 1)) ...
      Well, that's actually way different from what Blockhead was doing -- he was using "substr()" on a scalar ($line); substr() is not supposed to be used on an array (@lines).