Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl Regex To convert String to Hex Warns of uninitialized value or to use /x

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:

#$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?

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 .

like image 272
Bostwick Avatar asked Feb 19 '23 20:02

Bostwick


1 Answers

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

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/(.)/sprintf("%x",ord($1))/sexg
like image 178
ikegami Avatar answered May 18 '23 15:05

ikegami