Abdel
Abdel

Reputation: 6116

How do I skip a line/iteration if it produces an error?

I am using Bio::PopGen::PopStats to calculate Wright's Fst for each line I read in my input file. My input file consists of about 500,000 lines, so I calculate this statistic 500,000 times, as follows:

use Bio::PopGen::PopStats;
my $stats = Bio::PopGen::PopStats->new();
my $fst = $stats->Fst(\@populations,\@markernames);
push(@fsts, $fst);

I save each Fst value in the array @fsts because in the end I use all 500,000 Fsts to calculate some summary statistics.

If the module fails to calculate the Fst for one of the 500,000 lines, the whole Perl script stops and gives an error message, usually this one:

Illegal division by zero at /usr/share/perl5/Bio/PopGen/PopStats.pm line 292, <READ2> line 10878.

I would like my program to give this error message, but instead of stopping, just skip this line (put nothing in the @fsts array for this line), and finish the rest of the 500,000 lines. Any suggestions?

Upvotes: 1

Views: 699

Answers (2)

Eugene Yarmash
Eugene Yarmash

Reputation: 150128

You can use eval to trap fatal errors:

my $fst;
eval {
    $fst = $stats->Fst(\@populations,\@markernames);
    push @fsts, $fst;
    1;
} or warn $@;

Upvotes: 4

Igor Korkhov
Igor Korkhov

Reputation: 8558

Use an eval BLOCK:

my $fst = eval {
         $fst = $stats->Fst(\@populations,\@markernames)
         push(@fsts, $fst);
    } or {
         print $@;
    };

Upvotes: -1

Related Questions