Perl Regex将String转换为Hex未经初始化值的警告或使用/ x

时间:2022-03-09 19:30:50

I am using regex in perl to convert string to hex, however, when I do this, I get a warning from either perl critic or perl:

我在perl中使用正则表达式将字符串转换为十六进制,但是,当我这样做时,我会收到来自perl评论家或perl的警告:

#$test is defined, i just put the regex code snippet here...
#this will trigger a warning from perl critic
#warning: use of regex expression without "/x" expression..
$text =~  s/(.)/sprintf("%x",ord($1))/eg;

#this will trigger a a warning at run time 
#warning: "uninitialized value $1 in regexp compilation"
$text =~   m{s/(.)/sprintf("%x",ord($1))/eg}x;

Is there a way to write the above code that doesn't get a warning or feedback from Perl critic?

有没有办法编写上面的代码,没有得到Perl评论家的警告或反馈?

I think the issue is because ord is handling the undefined values, and when you put in /x then checking of the regex expression thinks that the value of $1 is invalid .

我认为问题是因为ord正在处理未定义的值,当你输入/ x时,检查regex表达式认为$ 1的值是无效的。

1 个解决方案

#1


8  

This critic is what is called a false positive. There's no need or reason for /x here. If you try to silence every critic, you'll end up with weird code. That said, the critic was recommending

这个批评者就是所谓的误报。这里没有/ x的需要或理由。如果你试图让每个评论家沉默,你最终会得到奇怪的代码。那就是评论家推荐的

s/(.)/sprintf("%x",ord($1))/exg

Furthermore, it probably makes no sense to avoid converting newlines. If so, you want to use /s too.

此外,避免转换换行符可能没有意义。如果是这样,你也想使用/ s。

s/(.)/sprintf("%x",ord($1))/sexg

#1


8  

This critic is what is called a false positive. There's no need or reason for /x here. If you try to silence every critic, you'll end up with weird code. That said, the critic was recommending

这个批评者就是所谓的误报。这里没有/ x的需要或理由。如果你试图让每个评论家沉默,你最终会得到奇怪的代码。那就是评论家推荐的

s/(.)/sprintf("%x",ord($1))/exg

Furthermore, it probably makes no sense to avoid converting newlines. If so, you want to use /s too.

此外,避免转换换行符可能没有意义。如果是这样,你也想使用/ s。

s/(.)/sprintf("%x",ord($1))/sexg