next if -f $subdir; #### next unless -d $subdir; #### foreach my $subdir ( sort @subdirs ) { chdir($dir); next unless -d $subdir; ... #### use strict; use warnings; use Cwd; use File::Path qw( make_path ); my $dir = cwd(); opendir(my $dh, $dir) or die "Unable to open directory '$dir': $!"; my @subdirs = readdir $dh or die "Unable to read directory '$dir': $!"; closedir $dh or die "Unable to close directory '$dir': $!"; my $result_path = $dir . '/results'; make_path $result_path; chdir $dir; for my $subdir (sort @subdirs) { chdir $dir; next unless -d $subdir; my $newdir = $result_path . '/' . $subdir; make_path $newdir; chdir $dir . '/' . $subdir; system("echo '1 0' | program -f methane.trr -o $result_path/$subdir/outfile.txt"); }