Why not use Cache::Cache to do the hard work for you? This will create a file cache (or a memory cache if that is what you want), of several directories deep (I even think it's configurable how deep you want it to be).
Comment on Re: Making a base32 representation of md5