Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Masking a string in perl using a mask string

Tags:

regex

perl

I have a string such as 'xxox-x' that I want to mask each line in a file against as such:

  • x's are ignored (or just set to a known value)
  • o's remain unchanged
  • the - is a variable length field that will keep everything else unchanged

therefore mask 'xxox-x' against 'deadbeef' would yield 'xxaxbeex'

the same mask 'xxox-x' against 'deadabbabeef' would yield 'xxaxabbabeex'

How can I do this succinctly preferrably using s operator?

like image 705
Reed Debaets Avatar asked Dec 09 '09 01:12

Reed Debaets


2 Answers

$mask =~ s/-/'o' x (length $str - length $mask)/e;
$str =~ s/(.)/substr($mask, pos $str, 1) eq 'o' ? $1 : 'x'/eg;
like image 144
ephemient Avatar answered Sep 22 '22 01:09

ephemient


$ perl -pe 's/^..(.).(.+).$/xx$1x$2x/;'
deadbeef
xxaxbeex
deadabbabeef
xxaxabbabeex
like image 28
caskey Avatar answered Sep 21 '22 01:09

caskey