http://www.perlmonks.org?node_id=253295

Eventually, everyone working in a *nix environment will have to pass things to the shell, but as everyone should be aware of by now, most homegrown quoting solutions are inadequate and breakable. I spent some effort researching semantics to write one that isn’t. The only situation this snippet can’t cope with is null bytes, because the shell eats those without providing any way to preserve them.

It’s likely to be less efficient than substitution based approaches, but I also find it a lot clearer and cleaner. Regex-based solutions feel to me like careful fiddling. This one is easy to grok, and any edge cases would be easily apparent (there aren’t any); when it comes to a job as critical as this one I’ll take the obviously deficiency-free approach over the fast one any day.

sub shell_quote { return join ' ', map { ( defined && length ) ? join q[\\'], map { (length) ? qq['$_'] : q[] } split /'/ +, $_, -1 : q['']; } @_; }