Some notes:
Will this work if $dir has at least one character >= 128? I think it needs 'use utf8;' and encoding it to the filesystem encoding before opendir call.
Will this work when all three encodings (filesystem, result file, code source file) aren't the same (Windows for example)? I doubt it