【问题标题】:Parsing in Perl a string separated by null bytes在 Perl 中解析由空字节分隔的字符串
【发布时间】:2012-06-20 13:03:18
【问题描述】:

/proc 文件系统包含正在运行的进程的详细信息。例如在 Linux 上,如果您的 PID 为 123,那么该进程的命令行将在 /proc/123/cmdline

中找到

cmdline 使用空字节来分隔参数。

我怀疑应该使用 unpack,但我不知道如何使用各种模板(“x”、“z”、“C*”、“H*”) 、“A*”等)只是没有用。

【问题讨论】:

  • 我的最终结果(能够读取原始命令行字符串)是通过 $line =~ s/\0/ /g; 实现的(感谢 lanzz 的启发)
  • my @cmd = $line =~ /([^\0]+)/g 可能更干净。然后,您可以根据需要简单地使用 "@cmd" 重新组装 cmd。

标签: perl null unpack


【解决方案1】:

一个简单的split("\0", $line) 就可以完成这项工作。

【讨论】:

    【解决方案2】:

    我实际上并不推荐使用它,但仅供参考:可以使用的解压模板是unpack "(Z*)*", $cmdlineZ 打包和解包以 null 结尾的字符串,但因为它是字符串类型,它是一个 长度 之后的数字或星号,而不是重复 - Z* 解包 一个 任意长度的以空字符结尾的字符串。要解压任何个,需要将其包装在括号中,然后对括号组应用重复,这会得到(Z*)*

    【讨论】:

    • 感谢您的澄清,很高兴了解有关打包/解包的知识。
    【解决方案3】:

    您可以将$/ 设置为"\0"。示例:

    perl -ne 'INIT{ $/ = "\0"} chomp; print "$_\n";' < /proc/$$/environ
    

    【讨论】:

      【解决方案4】:

      这可以通过命令行开关-l-0 来完成,或者通过手动更改$/ 来完成。

      -l-0 取决于顺序,可以多次使用。

      感谢您鼓励我阅读 perlrun 文档。

      例子:

      # -0    : set input separator to null
      # -l012 : chomp input separator (null) 
      #         and set output separator explicitly to newline, octol 012.
      # -p    : print each line
      # -e0   : null program
      
      perl -0 -l012 -pe0 < /proc/$$/environ
      

      .

      # -l    : chomp input separator (/n) (with -p / -n)
      #         and set output separator to current input separator (/n)
      # -0    : set input separator to null
      # -p    : print each line
      # -e0   : null program
      
      perl -l -0 -pe0 < /proc/$$/environ
      

      .

      # partially manual version
      # -l    : chomp input separator (/n) (with -p / -n)
      #         and set output separator to current input separator (/n)
      # -p    : print each line
      # -e    : set input record separator ($/) explicitly to null
      perl -lpe 'INIT{$/="\0"}'  < /proc/$$/environ
      

      捆绑问题:

      # DOESN'T WORK:
      # -l0   : chomp input separator (/n) (with -p / -n)
      #         and set output separator to \0
      # -e0   : null program
      perl -l0 -pe0
      

      .

      # DOESN'T WORK:
      # -0    : set input separator to null (\0)
      # -l    : chomp input separator (\0) (with -p / -n)
      #         and set output separator to current input separator (\0)
      # -e0   : null program
      perl -0l -pe1
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-02-06
        • 1970-01-01
        • 2019-12-04
        • 1970-01-01
        • 1970-01-01
        • 2011-01-11
        • 2015-03-29
        • 2014-07-19
        相关资源
        最近更新 更多