swissknife has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,

I want to achieve following. I have a string called bge1 and I want to convert it to bge:1. to make it more specific, search the substring in the end of string and if it is number replace it with :number. I am trying following

my $Interface = bge1; $Interface =~ s/[0-9]\$/:\$&/;

but still result is bge1

what is wrong with it?

Replies are listed 'Best First'.
Re: find a substring using regex and then replace it
by toolic (Bishop) on May 02, 2016 at 14:21 UTC
Re: find a substring using regex and then replace it
by hippo (Archbishop) on May 02, 2016 at 14:24 UTC

    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".

      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