Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I let perl interpret a string variable that represents an address

Tags:

perl

I want to feed input to a C program with a perl script like this ./cprogram $(perl -e 'print "\xab\xcd\xef";').

However, the string must be read from a file. So I get something like this: ./cprogram $(perl -e 'open FILE, "<myfile.txt"; $file_contents = do { local $/; <FILE> }; print $file_contents'. However, now perl interprets the string as the string "\xab\xcd\xef", and I want it to interpret it as the byte sequence as in the first example.

How can this be achieved? It has to be ran on a server without File::Slurp.

like image 932
codd Avatar asked Dec 14 '12 01:12

codd


1 Answers

In the first case, you pass the three bytes AB CD EF (produced by the string literal "\xAB\xCD\xEF") to print.

In the second case, you must be passing something other than those three bytes to print. I suspect you are passing the twelve character string \xAB\xCD\xEF to print.

So your question becomes: How does one convert the twelve-character string \xAB\xCD\xEF into the three bytes AB CD EF. Well, you'd require some kind of parser such as

s/\\x([0-9a-fA-F][0-9a-fA-F])|\\([^x])|([^\\]+)/
   $1 ? chr(hex($1)) : $2 ? $2 : $3
/eg

And here it is at work:

$ perl -e'print "\\xAB\\xCD\\xEF";' >file

$ echo -n "$( perl -0777pe'
     s{\\x([0-9a-fA-F][0-9a-fA-F])|\\([^x])|([^\\]+)}{
        $1 ? chr(hex($1)) : $2 // $3
     }eg;
  ' file )" | od -t x1
0000000 ab cd ef
0000003
like image 57
ikegami Avatar answered Oct 01 '22 22:10

ikegami