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.
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
using a bash trick:
perl -e "$(echo "print \"$(cat input)"\")"
which for your example becomes:
./cprogram "$(perl -e "$(echo "print \"$(cat myfile.txt)"\")")"
Is Perl's eval too evil? If not, end in print eval("\\"$file_contents\\"");
Or can you prepare the file in advance using Perl? EG print FILE "\\xAB\\xCD\\xED";
then read the resulting file with your existing code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.