Perl:使用正则表达式将十六进制编码的字符串解析为数组

发布于 2024-09-09 10:24:48 字数 361 浏览 3 评论 0原文

我对 Perl 开发很陌生,我想执行以下任务:

我的脚本接收十六进制编码的字符串作为命令行参数。然后我必须解码这个字符串并将其写入输出文件,如 C++ 数组,并根据给定的数据进行初始化。例如:

perl myscript.pl DEADBABEDEADBEEF 输出类似于

const boost::array; MyArray = { 0xDE, 0xAD, 0xBA, 0xBE, 0xDE, 0xAD, 0xBE, 0xEF };

使用 Perl 正则表达式执行此操作的正确方法是什么?当然,我可以用子字符串循环执行它,但我相信应该有更优雅的方式。

编辑:输入字符串是固定长度的。

I'm quite new to Perl development, and I'd like to perform a following task:

My script receives hex-encoded string as command-line param. Then I must decode this string and write it to output file like a C++ array with initialization from data given. For example:

perl myscript.pl DEADBABEDEADBEEF
and the output something like

const boost::array<char, 8> MyArray = { 0xDE, 0xAD, 0xBA, 0xBE, 0xDE, 0xAD, 0xBE, 0xEF };

What is the right way to do this with Perl regex? Of course, I could perform it in loop with substrings, but I believe that there should be more elegant way.

EDIT: the input string is of fixed length.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

淡笑忘祈一世凡恋 2024-09-16 10:24:48

试试这个:

my $hex = "DEADBABEDEADBEEF";
my @a = map "0x$_", $hex =~ /(..)/g;

它是如何工作的:

首先,列表上下文中的 $hex =~ /(..)/g 捕获所有 2 字符子字符串(/g 标志表示全局匹配)。然后 map() 获取列表并将其转换为另一个列表,对第一个列表的每个元素使用 "0x$_" 表达式 ($_< /code> 这里是元素的别名)。

另请参阅 perldoc -f map

Try this:

my $hex = "DEADBABEDEADBEEF";
my @a = map "0x$_", $hex =~ /(..)/g;

How it works:

First, $hex =~ /(..)/g in list context captures all 2-character substrings (the /g flag means global match). Then map() takes the list and transforms it to another one, using the "0x$_" expression for each element of the first list ($_ here is an alias for the element).

See also perldoc -f map.

烟酒忠诚 2024-09-16 10:24:48

这个怎么样:

my $input = $ARGV[0];
die "Fouled up input" unless $input =~ /^(?:[0-9A-F]{2})+$/i;
my $bytes = length ($input) / 2;
print "const boost::array<char, $bytes> MyArray = {";
while ($input =~ s/([0-9A-F]{2})//i) {
    # print $input # to see how this works, see comment.
    print "0x$1, ";
}
print "};\n";

How about this:

my $input = $ARGV[0];
die "Fouled up input" unless $input =~ /^(?:[0-9A-F]{2})+$/i;
my $bytes = length ($input) / 2;
print "const boost::array<char, $bytes> MyArray = {";
while ($input =~ s/([0-9A-F]{2})//i) {
    # print $input # to see how this works, see comment.
    print "0x$1, ";
}
print "};\n";
猫性小仙女 2024-09-16 10:24:48

拆包怎么样?

print join ",", unpack("(A2)*", "DEADBABEDEADBEEF");

更正 - 您需要一个映射来为解包返回的每个元素添加“0x”前缀

print join ",", map { '0x' . $_ } unpack("(A2)*", "DEADBABEDEADBEEF");

How about unpack?

print join ",", unpack("(A2)*", "DEADBABEDEADBEEF");

Correction - you'd need a map to prefix each element that unpack returns with a "0x"

print join ",", map { '0x' . $_ } unpack("(A2)*", "DEADBABEDEADBEEF");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文