in reply to Array of ($1, $2, ...) in replacement part of s///?

Nope, @-, @+, and substr is the way. People periodically suggest a @& variable to do what you want, but that would invoke all the drawbacks of $&.

One handy feature is that when you say $s =~ s/re/expr/ge within expr, $s will be the original $s and the offsets in @- and @+ will be offsets into the original $s, even if earlier matches changed the length of $s.

Would be nice if $& (and the vaporware @&) were usable in the substitution part of s/// without penalty...

Replies are listed 'Best First'.
Re: Re: Array of ($1, $2, ...) in replacement part of s///?
by flounder99 (Friar) on Jan 28, 2004 at 21:02 UTC
    Wow, I learn something new about perl every day.

    from perlvar:

    After a match against some variable $var: $` is the same as substr($var, 0, $-[0]) $& is the same as substr($var, $-[0], $+[0] - $-[0]) $' is the same as substr($var, $+[0]) $1 is the same as substr($var, $-[1], $+[1] - $-[1]) $2 is the same as substr($var, $-[2], $+[2] - $-[2]) $3 is the same as substr $var, $-[3], $+[3] - $-[3])
    so I wrote a test case:
    use strict; for my $regex (qr/(.)oo(.)ar(.)az/, qr/fo(.)barba(.)/) { my $str = "foobarbaz"; $str =~ s/$regex/ my @a; for my $index (1 .. $#+) { push @a, substr($str, $-[$index], $+[$index] - $-[$index]) +; } join "," , @a; /e; print "$str\n"; }
    outputs
    f,b,b o,z
    I'll have to remmember that one.

    --

    flounder

      And now in the usual idiom as well.

      join "," , map substr( $str, $-[$_], $+[$_] - $-[$_] ), 1 .. $#+;
        Reminds me of the old BBS days.
        join ",",map substr($str,$-[$_],$+[$_]-$-[$_]),1..$#+;#NO CARRIER

        --

        flounder