in reply to why can't I

Some output would help.

You need to close $f and closedir$fileDIR.

Check the readdir documentation.

Update:

My apologies for any confusion I may have caused - see my correction above. The main point is open and close need to match and opendir and closedir need to match.

-- Ken