I have actually been trying to write a similar workflow in perl and could not get it to work for some reason, but have to admit that my programming skills are more non-existant than rusty, so it is really no surprise.
I thought that it would be easy enough to implement David's suggestions with your script, but must be missing something, but as I said I have even less experience than you apparently, so it may be something quite basic.
I had intended to get a bit more into some basic scripting, but don't really have the time at the moment. Would you mind posting your completed workflow, or at least the corrected code you are using?
Thanks in advance!