electic!mp has asked for the wisdom of the Perl Monks concerning the following question:

hello Monks

i am embarrassed to be stumped both by the problem and by my inability to google around it

anyhow, trying to go from, for example "2.3" to "2.03". so, i try:

s{(\d\.)(\d)}{$10$2}

and obviously, the "$1" and the "0" get mushed together. i know i can do

s{(\d)\.(\d)}{$1.0$2} s{(\d.)(\d)}{$1."0".$2}e
...and many others

but my real question is, how does one separate variables from real stuff in the replacement?

e!

Replies are listed 'Best First'.
Re: separating replacements
by kcott (Archbishop) on Jan 01, 2017 at 01:18 UTC

    G'day electic!mp,

    Welcome to the Monastery.

    "... how does one separate variables from real stuff in the replacement?"

    Put braces around the name part of the variable. E.g.

    $ perl -E 'say 2.3 =~ s/(\d\.)(\d)/${1}0$2/r' 2.03

    — Ken

Re: separating replacements
by BrowserUk (Patriarch) on Jan 01, 2017 at 01:19 UTC

    What my formerly anonymous friend is saying is that anywhere that $??? is acceptable, ${???} is also acceptable; and means the same thing.

    The consequence of that is that whilst $12 addresses the 12th set of capture brackets; ${1}2 addresses the first set of capture brackets.


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority". The enemy of (IT) success is complexity.
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: separating replacements
by tybalt89 (Monsignor) on Jan 01, 2017 at 01:11 UTC
Re: separating replacements
by Lotus1 (Vicar) on Jan 01, 2017 at 23:40 UTC

    Your main question has been answered already but here are a couple of ideas I had that avoid using capturing groups. The first just replaces any '.' with '.0'. The second uses a lookbehind to find a digit and a '.' and a lookahead to check for a digit and then inserts a '0'. I looked around for a numeric version of \b for matching number boundaries but didn't see anything.

    use strict; use warnings; my $num1 = 2.3; print "$num1 -> "; $num1 =~ s/\./.0/; print "$num1\n"; $num1 = 2.3; print "$num1 -> "; $num1 =~ s/(?<=\d\.)(?=\d)/0/; print "$num1\n"; __DATA__ 2.3 -> 2.03 2.3 -> 2.03