« Seattle Coffee Works | Main | Killer Cars »

Shell Escapes in Perl Example

Example why Shell Escapes in Perl are usually a mistake. Problems with the PATH and similar portability problems will not be discussed.

`find $dir $prune -o -type f -print0 \ | xargs -0 grep @Args \ | grep -v '^[ ]*--'`

No idea what the user on #perl was trying to accomplish, claimed their use case require this horrid escape. Problems include the need to run quotemeta on the interpolated variables, ensuring $prune is not empty (otherwise find(1) blows up). No idea why @Args is an array, as $" can influence how an array will interpolate, which would change the grep(1) results unexpectedly. And, more than one element would break grep

Error handling and debugging also problematic: if nothing returned, is that expected, or due to a bug somewhere in the pipe chain ($dir not a directory or permissions problem; $prune not set; grep(1) passed regular expression with a typo; other)? Where is standard error going, in the event an exit code is not zero?

Better code would use the File::Find or similar module, read through the files, skip unwanted lines, and return the matches. More lines than the shell code takes to write, but easier to debug, and far more portable.

Technorati Tags: