Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing in Perl a string separated by null bytes

Tags:

null

perl

unpack

The /proc filesystem contains details of running processes. For example on Linux if your PID is 123 then the command line of that process will be found in /proc/123/cmdline

The cmdline is using null-bytes to separate the arguments.

I suspect unpack should be used but I don't know how, my miserable attempts at it using various templates ("x", "z", "C*", "H*", "A*", etc.) just did not work.

like image 681
emx Avatar asked Jun 18 '12 14:06

emx


3 Answers

This can be done with the command line switches -l and -0, or by manually changing $/.

-l and -0 are order dependent and can be used multiple times.

Thanks for inspiring me to read perlrun documentation.

examples:

# -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

bundling issues:

# 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
like image 196
spazm Avatar answered Sep 20 '22 10:09

spazm


A simple split("\0", $line) would do the job just fine.

like image 9
lanzz Avatar answered Oct 21 '22 10:10

lanzz


You can set $/ to "\0". Example:

perl -ne 'INIT{ $/ = "\0"} chomp; print "$_\n";' < /proc/$$/environ
like image 5
Vi. Avatar answered Oct 21 '22 11:10

Vi.