in reply to Re^3: regex question
in thread regex question

if you capture something by () in regex and you get $1,$2,$3 and so on, why can't you just do
s/$2/something/
In this script, it's doing it but it's changing the value rather than position. What i mean is,
[root@myserver tmp]# cat perl.test #!/usr/bin/perl -w use strict; my $string = "123 123 345"; if ("$string" =~ /(\d+)\s+(\d+)\s+(\d+)/) { $string =~ s/$2/something/; print "$string\n"; } [root@myserver tmp]# ./!$ ./perl.test something 123 345
I wanted this to change the value of position $2, Therefore wanted to see
123 something 345

Replies are listed 'Best First'.
Re^5: regex question
by johngg (Canon) on Nov 12, 2007 at 19:21 UTC
    That happens because your second capture, held in $2, is "123" so in your substitution inside the if $2 is interpolated to give s/123/something/, which runs quite happily and replaces the first occurence of "123" in $string. Had your string been "987 123 345" your code would have given the result you wanted but only as a side effect of your error. You could do it like this (not tested)

    use strict; use warnings; my $string = q{123 123 345}; if ( $string =~ s{^(\d+\s+)(?:\d+)(\s+\d+)}{$1something$2} ) { print qq{Succeeded\n$string\n}; } else { print qq{Failed\n$string\n}; }

    I hope this makes things a bit clearer.

    Cheers,

    JohnGG