Some comments:
- I prefer to almost always use a defined "my $variable" in a loop, especially when using nested loops each of which use $_. Doing otherwise can lead to problems. Using a "my" variable instead of $_ is very "cheap" execution time wise.
- Normally assigning $_ to a variable is not needed. Do that as part of the loop setup.
- In the "die" message, a trailing "\n" will suppress the Perl line number upon which the error occurred. For code like this, normally you will want a direct reference to the line number where the open failed, so don't put a trailing "\n". In some user programs, maybe the actual line number is confusing and you want a \n to suppress that. In any event, be aware of this difference.
- Normally do not put a trailing "/" at the end of the directory name. This can at least confuse Windows on occasion. Prepend a "/" when expanding the path, "$dir/$sub_dir/$file".
- Of course, readdir() returns just a name, not the full path, so that needs to be corrected in the open().
I think this should work, (untested):
my $dir = "directory"; #### no trailing "/"
opendir ( DH, $dir ) || die "Cannot open $dir: $!"; #### no "\n"
foreach my $file ( readdir DH) # Note: only name, not full path
{
next unless $file =~ /\.fa$/;
open (READ, '<', "$dir/$file") || die "Cannot open $dir/$file: $!";
+
while (my $line =<READ>)
{
if ($line =~ /^>/)
{
print $line;
}
}
close READ;
}
close (DH);