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;
CodePudding user response:
The s///
is a regex substitution operator which the =~
operator binds to a variable on its left-hand side
$var =~ s/pattern/replacement/;
matches the pattern in the variable $var
and performs a substitution of it by the replacement string. This 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 statement
(my $new_var = $original) =~ s/.../.../;
Now $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.14
my $new_var = $original =~ s/.../.../r;
The $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 then chr
on what hex
returns, and uses that result to replace them. It keeps going through the string to do that with all such pairs that it finds.
†
Here the modifiers are: e
, which makes is so that the replacement side is evaluated as code and what it returns is used for replacement, and g
which makes it continue searching and replacing through the whole string (not just the first occurrence of pattern
that is found).