Reputation: 25
Perl substitute all Numbers to Alphabet
abc4xyz5u
to
abcdxyzeu
I try this,but it not work:
echo 'abc4xyz5u' | perl -pe'@n=1..9;@a=a..j;@h{@n}=@a;s#$n[$_]#$h{$&}#g for 0..$#n'
I know y/[1-9]/[a-j]/, but I want to use a substitute.
Upvotes: 2
Views: 379
Reputation: 6626
Your issue is within
s#$n[$_]#$h{$&}#g for 0..$#n
You expect $_
to be your input (so that s###
is applied on it), but also $n[$_]
to use the $_
from the for loop (0
to $#n
). If you were to add a print, you'd notice that $_
's value within this loop is 0
to $#n
, rather than your input.
What you could do instead to fix it is something like:
$r=$_; $r=~s#$n[$_]#$h{$&}#g for 0..$#n; $_=$r
But that's much more complicated that it has to be. I would instead do:
s#([1-9])#$h{$1}#g
Or, without using %h
(since, let's face it, an hash with 0 => a
, 1 => b
etc. should be an array):
perl -pe '@a="a".."j"; s#([1-9])#$a[$1-1]#g'
Or, without requiring an array at all (I'll let you decide if you find it easier or harder to read; personally I'm fine with it),
perl -pe 's/([1-9])/chr(ord("a")+$1-1)/ge'
Upvotes: 3
Reputation: 556
I would suggest to write it properly as a perl script. The one liner you mentioned is little hard to understand.
use strict;
use warnings;
my @alphabets = ("a".."z");
my $input = $ARGV[0];
$input =~ s/(\d)/$alphabets[$1 - 1]/g;
print $input;
Run -
perl substitute.pl abc4xyz5u
Output -
abcdxyzeu
I am serching for the number in the string and replacing it with the alphabet on the same position(remenber array start form 0 index and hence 'position -1') in the 'alphabets' array
Upvotes: 1