わざわざ chdir せずに
open OUT, "> temp/$dirname/test.txt" or die "can't create the file\n";
ってすればいいじゃない