Question

I'm a self-taught Perler, seeking assistance from the Perl experts:

I keep getting an error saying I can't use the filehandle within a foreach loop, even though I'm sure to close it (or undef it, I've tried both). See the full error here: http://cl.ly/image/2b2D1T403s14

The code is available on GitHub: https://github.com/bsima/yeast-TRX

The code in question can be found in the file "script.pl" at around line 90:

foreach my $species (keys %Saccharomyces) {
    open(RAW,">./data/$species/$geneName/raw.csv");
        print RAW "gene,dinucleotide,position,trx.score,energy.score\n";
    undef RAW; 
    open(SMOOTH,">./data/$species/$geneName/smooth.csv");
        print SMOOTH "gene,position,trx.score,energy.score\n";
    undef SMOOTH;
}

Help is much appreciated! I don't know the intricacies of how Perl works with filehandles, probably because of my lack of formal training. Any comments on my overall code quality is welcome too, if someone is feeling particularly helpful.

EDIT: Found the problem. Perl cannot generate directories on the fly, so the $species/$geneName directory was never even being created. I added a line at the beginning of the foreach loop that said simply mkdir("$species/$geneName"); and that solve the issue.

Was it helpful?

Solution 2

Perl cannot generate directories on the fly, so the $species/$geneName directory was never even being created. I added a line at the beginning of the foreach loop that said simply mkdir("$species/$geneName"); and that solve the issue.

OTHER TIPS

You are getting warning that is quite telling:

Bareword RAW not allowed while "strict subs" in use

Also, undef FILEHANDLE is not as good as close FILEHANDLE.

Solution is to use normal scoped variables for file handles and close them, something like this:

foreach my $species (keys %Saccharomyces) {
    open my $raw, ">", "./data/$species/$geneName/raw.csv";
    print $raw "gene,dinucleotide,position,trx.score,energy.score\n";
    close $raw;
    open my $smooth, ">", "./data/$species/$geneName/smooth.csv";
    print $smooth "gene,position,trx.score,energy.score\n";
    close $smooth;
}

Also, you should check if $raw and $smooth were opened before trying to write to them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top