How can I safely pass a filename with spaces to an external command in Perl?

后端 未结 3 1436
[愿得一人]
[愿得一人] 2020-12-10 17:07

I have a Perl script that processes a bunch of file names, and uses those file names inside backticks. But the file names contain spaces, apostrophes and other funky charact

3条回答
  •  天涯浪人
    2020-12-10 17:11

    Are you looking for quotemeta?

    Returns the value of EXPR with all non-"word" characters backslashed.

    Update: As hobbs points out in the comments, quotemeta is not intended for this purpose and upon thinking a little more about it, might have problems with embedded nuls. On the other hand String::ShellQuote croaks upon encountering embedded nulls.

    The safest way is to avoid the shell entirely. Using the list form of 'system' can go a long way towards that (I found out to my dismay a few months ago that cmd.exe might still get involved on Windows), I would recommend that.

    If you need the output of the command, you are best off (safety-wise) opening a pipe yourself as shown in hobbs' answer

提交回复
热议问题