Can someone please explain what tr#A-Za-z0-9+/# -_#; means in perl?

Can someone please explain what tr#A-Za-z0-9+/# -_#; means in perl?

Looks like a base64 encoding thing.

prolly not.

tr#A-Za-z0-9+/# -_#; 

== turn an alphanumeric string (if that is something you know) into '-_' where _
is a reserved word in perl regex that means a word separator. i.e., replace alphanum words
witj the hyphen

That's not really the case here.

Perl expands character ranges specified by the hyphen character ("-") in the tr operator.

So, in this expression:

tr#A-Za-z0-9+/# -_#

the SEARCHLIST (in red) is just a compact form of

(a) all characters from "A" to "Z", and
(b) all characters from "a" to "z", and
(c) all characters from "0" to "9", and
(d) the characters "+" and "/"

i.e. this -

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/

The REPLACEMENTLIST (in green) is a compact form of

(a) all characters from space (" ") to underscore character ("_")

i.e. this -

 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_

And the tr operator simply transliterates all characters in SEARCHLIST with the corresponding character in REPLACEMENTLIST.

The mapping could be seen better this way -

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_

You can test this like so -

$
$
$ # "ABCD" maps to "space, exclamation mark, double quote, hash character" therefore
$
$ echo "ABCD" | perl -plne 'tr#A-Za-z0-9+/# -_#'
 !"#
$
$
$ # "0123" maps to "TUVW"
$
$ echo "0123" | perl -plne 'tr#A-Za-z0-9+/# -_#'
TUVW
$
$
$ # "c" maps to "<", "+" maps to "^", "t" maps to "M", so "c+t" maps to "<^M"
$
$ echo "c+t" | perl -plne 'tr#A-Za-z0-9+/# -_#'
<^M
$
$
$ # any other character is left as it is
$
$ echo "$~%=" | perl -plne 'tr#A-Za-z0-9+/# -_#'
$~%=
$
$
$ # check the entire SEARCH list, with unmapped character "~" at the end
$
$ echo "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/~" | perl -plne 'tr#A-Za-z0-9+/# -_#'
 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_~
$
$
$

HTH,
tyler_durden

3 Likes

Yes, after the replacement, you can take away the lower 6 bits for your base64 to binary conversion.