Search code examples
perltr

Perl tr replace but ignore first 2 characters


I need convert $foo= 101100 to 10aabb

Currently using this but it replaces entire string

$foo =~ tr/10/ab/;


Solution

  • Here's some Perl magic for you:

    my $foo = 101100;
    substr($foo, 2) =~ tr/10/ab/;
    print $foo;
    

    Output:

    10aabb
    

    Basically we take the substring of the string, starting at the 2nd character offset, and transliterate it.

    In the documentation for substr you can read about this:

    You can use the substr function as an lvalue, in which case EXPR must itself be an lvalue.
    ...
    When used as an lvalue, specifying a substring that is entirely outside the string raises an exception. Here's an example showing the behavior for boundary cases:

    my $name = 'fred';
    substr($name, 4) = 'dy';         # $name is now 'freddy'
    my $null = substr $name, 6, 2;   # returns "" (no warning)
    my $oops = substr $name, 7;      # returns undef, with warning
    substr($name, 7) = 'gap';        # raises an exception