Tamim Chowdhury
Tamim Chowdhury

Reputation: 97

Converting byte array to decimal

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;

Upvotes: 1

Views: 79

Answers (1)

zdim
zdim

Reputation: 66883

The s/// is a regex substitution operator which the =~ operator binds to a variable on its left-hand side, so a statement

$var =~ s/pattern/replacement/;

matches 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 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.

If this is indeed precisely all that there is to do then it is more simply done using pack

my $bytearray_val_ascii = pack( "H*", $in );

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; and g which makes it continue searching and replacing through the whole string (not just the first occurrence of pattern that is found).

Upvotes: 4

Related Questions