user2886545
user2886545

Reputation: 713

String comparison in Perl

I have an array of sequences:

@array = (AAABBBBBCCCCCDDDDD,AEABCBBBCCECCDDDDD...); #up to 55 sequences

I want to compare each position of each sequence. In other words, first position of the sequences shown is A, so they are the same. I'd like to have a counter that indicates how many positions don't have the same letter for every string.

AAABB
AAABC
AAABB #5th position is not equal, so result is 1.

print $counter -----> 1.

I know how to do it with 2 sequences:

my $string1 = 'AAABBBBBCCCCCDDDDD';
my $string2 = 'AEABBBBBCCECCDDDDD';
my $result = '';
for(0 .. length($string1)) {
    my $char = substr($string2, $_, 1);
    if($char ne substr($string1, $_, 1)) {
        $counter++;
    }
}
print $counter;

The problem is that I have 55 sequences in an array.

Upvotes: 0

Views: 118

Answers (2)

ikegami
ikegami

Reputation: 385657

You had the right approach in the first part of your question: Use an array.

my @strings = qw( AAABBBBBCCCCCDDDDD AEABBBBBCCECCDDDDD );
my $result = '';

my $counter = 0;
for my $pos (0 .. length($strings[0])) {
    my $char = substr($strings[0], $pos, 1);
    for my $i (1..$#strings) {
       if (substr($strings[$i], $pos, 1) ne $char) {
          ++$counter;
          last;
       }
    }
}

print "$counter\n";

Upvotes: 1

Mark Setchell
Mark Setchell

Reputation: 207445

Huh? If every letter has to be the same in every one of the 55 or so strings, there is no need to look at individual letters, surely? The whole strings must be equal, so this answers the question:

#!/usr/bin/perl
use strict;
use warnings;

my @array = qw(AAABBBBBCCCCCDDDDD AEABBBBBCCECCDDDDD APPLE); 
for my $i (1..$#array){
   print "$array[$i] isn't same as $array[0]\n" if $array[$i] ne $array[0];
}

Upvotes: 0

Related Questions