将字节数组转换为十进制
想知道是否有人可以向我深入解释这个片段
(my $bytearray_val_ascii = $in) =~ s/([a-fA-F0-9]{2})/chr(hex $1)/eg;
Was wondering if someone could explain this snippet to me in depth
(my $bytearray_val_ascii = $in) =~ s/([a-fA-F0-9]{2})/chr(hex $1)/eg;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
s///
是一个正则表达式 替换运算符< /a> 其中=~
运算符 绑定到其左侧的变量,因此语句与变量
$var
中的模式匹配,并通过以下方式执行替换替换字符串,在双引号上下文中计算。该操作可以通过跟随结束分隔符的 修饰符 进行调整和调整(也可以是嵌入到模式中)。†这会“就地”更改变量——在此语句
$var
更改之后。保留$var
并将更改后的字符串存储在另一个变量中的习惯用法是将$var
分配给该另一个变量,然后“然后”更改它(通过用括号对操作进行排序) ,尽在一份声明中。常用的习惯用法是在该语句中引入一个新变量,现在
$original
未更改,而更改后的字符串位于$new_var
中(如果模式 匹配)。由于引入了
r
(非破坏性)修饰符,现在不需要这个惯用语在 5.14 中,$original
保持不变,返回更改后的字符串,然后分配给$new_var
。正则表达式本身匹配并捕获两个连续的字母数字字符,对它们运行
hex
,然后对hex
返回的内容运行chr
,并使用该结果来替换他们。它会不断遍历字符串,以对找到的所有此类对执行此操作。如果这确实是要做的全部事情,那么使用 pack 可以更简单地
完成sup>†
这里的修饰符是:
e
,它使得替换侧被评估为代码,以便该代码评估的内容用于替换;和g
,这使得它继续搜索和替换整个字符串(而不仅仅是找到的第一次出现的pattern
)。The
s///
is a regex substitution operator which the=~
operator binds to a variable on its left-hand side, so a statementmatches the pattern in the variable
$var
and performs a substitution of it by the replacement string, evaluated in a double-quoted context. The operation can be tuned and tweaked by modifiers that follow the closing delimiter (and which can also be embedded in the pattern).†This changes the variable "in-place" -- after this statement
$var
is changed. An idiom to preserve$var
and store the changed string in another variable is to assign$var
to that other variable and "then" change it (by ordering operations by parenthesis), all in one statement. And the commonly used idiom is to also introduce a new variable in that statementNow
$original
is unchanged, while the changed string is in$new_var
(if the pattern matched).This idiom is nowadays unneeded since a
r
(non-destructive) modifier was introduced in 5.14The
$original
is unchanged and the changed string returned, then assigned to$new_var
.The regex itself matches and captures two consecutive alphanumeric characters, runs
hex
on them and thenchr
on whathex
returns, and uses that result to replace them. It keeps going through the string to do that with all such pairs that it finds.If this is indeed precisely all that there is to do then it is more simply done using pack
†
Here the modifiers are:
e
, which makes is so that the replacement side is evaluated as code so that what that code evaluates to is used for replacement; andg
which makes it continue searching and replacing through the whole string (not just the first occurrence ofpattern
that is found).