I'm trying to use a foreach loop to loop through an array and then use a nested while loop to loop through each line of a text file to see if the array element matches a line of text; if so then I push data from that line into a new array to perform calculations.
The outer foreach loop appears to be working correctly (based on printed results with each array element) but the inner while loop is not looping (same data pushed into array each time).
Any advice?
The code is below
#! /usr/bin/perl -T
use CGI qw(:cgi-lib :standard);
print "Content-type: text/html\n\n";
my $input = param('sequence');
my $meanexpfile = "final_expression_complete.txt";
open(FILE, $meanexpfile) or print "unable to open file";
my @meanmatches;
@regex = (split /\s/, $input);
foreach $regex (@regex) {
while (my $line = <FILE>) {
if ( $line =~ m/$regex\s(.+\n)/i ) {
push(@meanmatches, $1);
}
}
my $average = average(@meanmatches);
my $std_dev = std_dev($average, @meanmatches);
my $average_round = sprintf("%0.4f", $average);
my $stdev_round = sprintf("%0.4f", $std_dev);
my $coefficient_of_variation = $stdev_round / $average_round;
my $cv_round = sprintf("%0.4f", $coefficient_of_variation);
print font(
{ color => "blue" }, "<br><B>$regex average: $average_round
 Standard deviation: $stdev_round Coefficient of
variation(Cv): $cv_round</B>"
);
}
sub average {
my (@values) = @_;
my $count = scalar @values;
my $total = 0;
$total += $_ for @values;
return $count ? $total / $count : 0;
}
sub std_dev {
my ($average, @values) = @_;
my $count = scalar @values;
my $std_dev_sum = 0;
$std_dev_sum += ($_ - $average)**2 for @values;
return $count ? sqrt($std_dev_sum / $count) : 0;
}
use strictanduse warningsat the top of every Perl program that you write. They are invaluable aids to finding problems with your code, and withoutuse strictthere is little point in usingmyto declare anything. In this case,use strictreveals that you have failed to declare either@regexor$regex.