Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm really confused about how to pass a variable into different statement. My code is:

use warnings;
use strict;
use feature qw(say);

say "Please enter the first sequence:";
my $sequence1 = <STDIN>;
$sequence1 = chomp $sequence1;
say "Please enter the second sequence:";
my $sequence2 = <STDIN>;
$sequence2 = chomp $sequence2;

if (length $sequence1 < length $sequence2){
        my $sequence2_new = substr $sequence2, length $sequence1;
}

my @sequence1 = split(',', $sequence1);
my @sequence2 = split(',', $sequence2_new);
my $element = scalar @sequence1;

my $num = 0;
for ($a = 0; $a < $element; $a++){
        if ($sequence1[$a] = $sequence2[$a]){
                $num++;
        }
}

my $score = $num % length $sequence2;
say "The alignment score is: $score";

In this case, this program will return a Global symbol "$sequence2_new" requires explicit package name at alignment_sequence.pl line 19.mistake. If I move the "my" declaration in front of if statement in line 14 like my $sequence2_new; it will give me Use of uninitialized value $sequence2_new in split at alignment_sequence.pl line 20, <STDIN> line 2. warning.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
185 views
Welcome To Ask or Share your Answers For Others

1 Answer

You need to declare my $sequence2_new outside the if statement. As you have it, the variable's life ends at the close of the if block

Note also that

$sequence1 = chomp $sequence1

is wrong. It will set $sequence1 to the number of characters that chomp removed—probably 1 or 0. You want just

chomp $sequence1

You also have if ( $sequence1[$a] = $sequence2[$a] ) { ... } which is an assignment. Presumably you want the comparator eq here?

Here's how I think your code should look, but I'm not at all sure about chopping off the beginning of $sequence2 if it is longer than $sequence1; that doesn't seem at all right, but I have no way of knowing for sure

use strict;
use warnings;
use feature qw(say);

print "Please enter the first sequence: ";
chomp ( my $sequence1 = <> );

print "Please enter the second sequence: ";
chomp ( my $sequence2 = <> );

my $sequence2_new;
if ( length $sequence1 < length $sequence2 ) {
    $sequence2_new = substr $sequence2, length $sequence1;
}

my @sequence1 = split /,/, $sequence1;
my @sequence2 = split /,/, $sequence2_new;

my $num = 0;

for my $a ( 0 .. $#sequence1 ) {

    ++$num if $sequence1[$a] eq $sequence2[$a];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...