I have below string which I want to replace individual characters using perl regular expression
Input : War started
Output: 12345623689
W>1,a->2,r->3,space->4,s->5,t->6,a->2,r->3,t->6,e->8,d->9
Kindly suggest. My objective is just to mask the data and i should be able to unmask it later
I tried with S/W/1
But how to combine all in together
CodePudding user response:
my $s = 'War started';
my %map;
my $coded = $s =~ s{.}{ $map{$&} //= keys(%map) }segr;
say $coded; # 12345623678
(Note that you had ..89 instead of ..78.)
Obviously, you could use a pre-built mapping just as easily.
my %map = (
"W" => 1,
"a" => 2,
"r" => 3,
" " => 4,
"s" => 5,
"t" => 6,
"e" => 8,
"d" => 9,
);
my $s = 'War started';
my $coded = $s =~ s{.}{ $map{$&} // "?" }segr;
say $coded; # 12345623689
CodePudding user response:
You could use tr///
:
my $str = 'War started';
$str =~ tr/War sted/12345689/;
say $str;
To decrypt it, you just make a reverse mapping.