This is *dangerous* code snippet, because it corrupts value of $_ variable by while($_=readdir). (didn't you read "seven sins of perl (revisited)?")
You should place local $_ somewhere at the beginning of a sub. Or write instead of "while" ..... for (readdir)
which will localize $_ itself.