in reply to numbers masking

Do you need to keep the "separators"? If not, just remove the separators from the string (e.g.  s/[^0-9]//g), and use the method you already have.

Replies are listed 'Best First'.
Re^2: numbers masking
by Anonymous Monk on May 16, 2012 at 07:04 UTC

    I need to keep the seperators as it is

      A bit tedious then:
      #!/usr/bin/perl use warnings; use strict; use Test::More; sub mask { my $num = shift; my ($begin, $end) = (q{}, q{});; $begin .= substr $num, 0, 1, q{} until 7 == $begin =~ tr/0-9 +//; $num = substr($begin, -1, 1, q{}) . $num; $end = substr($num, -1, 1, q{}) . $end until 5 == $end =~ tr/0-9 +//; $num .= substr $end, 0, 1, q{}; $num =~ tr/0-9/X/; return $begin . $num . $end; } is(mask($_->[0]), $_->[1]) for ( ['1234 5678 1234 5678' , '1234 56XX XXXX 5678'], ['1234567812345678' , '123456XXXXXX5678'], ['5413 21069873210200' , '5413 21XXXXXXXX0200'], ['541321069873210200' , '541321XXXXXXXX0200'], ['1234/1234-5678-9012:34' , '1234/12XX-XXXX-XX12:34'] ); done_testing();
      Update: Fixed error in tr, thanks, jwkrahn.
        $begin .= substr $num, 0, 1, q{} until 7 == $begin =~ tr/[0- +9]//; ... $end = substr($num, -1, 1, q{}) . $end until 5 == $end =~ tr/[0- +9//; ... $num =~ tr/[0-9]/X/;

        You are including the [ and ] characters but the OP only wants to change numerical digits.

        $begin .= substr $num, 0, 1, q{} until 7 == $begin =~ tr/0-9 +//; ... $end = substr($num, -1, 1, q{}) . $end until 5 == $end =~ tr/0-9 +//; ... $num =~ tr/0-9/X/;