Search code examples
perlencodingbase64decoding

decode / encode base64 perl


People on stackoverflow helped me with a base64 decoding in Perl but I would like to have the script in reverse :

use strict;
use warnings;

use MIME::Base64;

my $str = 'CS20UumGFaSm0QXZ54HADg';

my @chars = split //, decode_base64 $str;
my @codes = map ord, @chars;
print "@codes\n";

Output = 9 45 180 82 233 134 21 164 166 209 5 217 231 129 192 14

Now I would like to have the output as my $str and CS20UumGFaSm0QXZ54HADg as output? I've been trying it for some hours but can't seem to get it right.


Solution

  • Use chr as the inverse of ord.

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    use MIME::Base64;
    
    my @array = qw(9 45 180 82 233 134 21 164 166 209 5 217 231 129 192 14);
    
    my $str = encode_base64(join '', map chr, @array);
    
    print $str, "\n";
    

    Outputs:

    CS20UumGFaSm0QXZ54HADg==
    

    This is stated in perldoc (emphasis mine):

    • ord EXPR
    • ord

      Returns the numeric value of the first character of EXPR. If EXPR is an empty string, returns 0. If EXPR is omitted, uses $_. (Note character, not byte.)

      For the reverse, see chr. See perlunicode for more about Unicode.