Parl parsing a string separated by null bytes

The / proc file system contains information about running processes. For example, on Linux, if your PID is 123 , then the command line of this process will be found in / proc / 123 / cmdline

cmdline uses null bytes to separate arguments.

I suspect that unpacking should be used, but I don’t know how, my pathetic attempts to use it with various patterns ("x", "z", "C *", "H *", "A *", etc. d.) It just doesn't work.

+8
null perl unpack
source share
4 answers

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

+8
source share

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

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

I really do not recommend using this, but only for your information: the unpacking template that would work was unpack "(Z*)*", $cmdline . Z packs and unpacks lines with a terminating zero, but due to the fact that it is a type of line, number or star after length, and not repetition - Z* unpacks one line with zero termination of arbitrary length. To unpack any number of them, you need to wrap it in parentheses and then apply the repetition to the group in brackets that gets you (Z*)* .

+3
source share

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

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

Thanks for inspiring me to read the 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 

problems with the kit:

 # 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 
0
source share

All Articles