There are two simple steps to "making it work right":
Make it work right on the shell command line without Perl
Make it work within Perl
As soon as your command works under condition 1, it will also work under condition 2. Currently, you will find that your approach does not work under condition 1. Fix that.