in reply to find a substring using regex and then replace it

There are 2 problems there: you are using bge1 as a bareword and you are escaping the dollars in the regex thus preventing them from doing what you want. Here's the working version:

#!/usr/bin/env perl use strict; use warnings; my $Interface = 'bge1'; $Interface =~ s/[0-9]$/:$&/; print $Interface . "\n";

which outputs "bge:1".

Replies are listed 'Best First'.
Re^2: find a substring using regex and then replace it
by johngg (Canon) on May 02, 2016 at 16:08 UTC

    It's unlikely but not beyond the realms of possibility to have more than ten interfaces so it would be safer to match for one or more (+) digits at the end of the string. This gives the wrong result:-

    $ perl -Mstrict -Mwarnings -E ' my $interface = q{bge12}; $interface =~ s{[0-9]$}{:$&}; say $interface;' bge1:2 $

    This corrects the problem. I also prefer to use the \d special escape for digits and a look-ahead to save having to mention what was matched in the replacement part:-

    $ perl -Mstrict -Mwarnings -E ' my $interface = q{bge12}; $interface =~ s{(?=\d+$)}{:}; say $interface;' bge:12 $

    I hope this is of interest.

    Cheers,

    JohnGG