[英]How can I let perl interpret a string variable that represents an address
I want to feed input to a C program with a perl script like this ./cprogram $(perl -e 'print "\\xab\\xcd\\xef";')
. 我想使用这样的perl脚本将输入提供给C程序
./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. 所以我得到这样的东西:
./cprogram $(perl -e 'open FILE, "<myfile.txt"; $file_contents = do { local $/; <FILE> }; print $file_contents'
。但是,现在perl解释了字符串作为字符串"\\xab\\xcd\\xef"
,我希望它像第一个示例一样将其解释为字节序列。
How can this be achieved? 如何做到这一点? It has to be ran on a server without File::Slurp.
它必须在没有File :: Slurp的服务器上运行。
In the first case, you pass the three bytes AB CD EF
(produced by the string literal "\\xAB\\xCD\\xEF"
) to print
. 在第一种情况下,您将三个字节
AB CD EF
(由字符串文字"\\xAB\\xCD\\xEF"
)传递给print
。
In the second case, you must be passing something other than those three bytes to print
. 在第二种情况下,您必须传递除这三个字节以外的其他内容以进行
print
。 I suspect you are passing the twelve character string \\xAB\\xCD\\xEF
to print
. 我怀疑您正在传递十二个字符串
\\xAB\\xCD\\xEF
进行print
。
So your question becomes: How does one convert the twelve-character string \\xAB\\xCD\\xEF
into the three bytes AB CD EF
. 因此,您的问题变成:如何将十二个字符的字符串
\\xAB\\xCD\\xEF
转换为三个字节的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: 使用bash技巧:
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? Perl的评估太邪恶了吗? If not, end in
print eval("\\"$file_contents\\"");
如果不是,
print eval("\\"$file_contents\\"");
结尾print eval("\\"$file_contents\\"");
Or can you prepare the file in advance using Perl? 还是可以使用Perl预先准备文件? EG
print FILE "\\xAB\\xCD\\xED";
EG
print FILE "\\xAB\\xCD\\xED";
then read the resulting file with your existing code. 然后使用现有代码读取结果文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.