in reply to Modifying the match position after each match

Some other variations:

use strict; use warnings; use 5.010; my $string = "_'nada_komo_el_'sol_"; $string =~ s/_'?(.)/_'$1/g; say $string; --output:-- _'nada_'komo_'el_'sol_

---

use strict; use warnings; use 5.010; my $string = "_'nada_komo_el_'sol_"; my @pieces = split /_'?/, $string; say join(q{_'}, @pieces); --output:-- _'nada_'komo_'el_'sol

Replies are listed 'Best First'.
Re^2: Modifying the match position after each match
by pat_mc (Pilgrim) on Mar 24, 2010 at 09:03 UTC
    I believe that I need to include executable Perl code in the regex to reduce the match position variable after each matching string. Then ALL substrings of format _[^']+?_ should be matched:
    #! /usr/bin/perl -w use strict; use locale; my $string1 = "_'nada_komo_el_'sol_"; my $string2 = "_na'da_komo_el_so'l_"; $string1 =~ s/(_)([^']+?)(_)(?{pos($string1) --})/$1'$2$3/go; $string2 =~ s/(_)([^']+?)(_)(?{pos($string2) --})/$1'$2$3/go; print "String 1: $string1 \n"; print "String 2: $string2 \n";

    But somehow, this is not working for me and I get
    --output:-- String 1: _'nada_'komo_el_'sol_ String 2: _na'da_'komo_el_so'l_
    Any ideas as to why this is happening?

    Your wisdom is much appreciated ...

    Pat

      You're working much to hard:

      #! /usr/bin/perl -w use strict; use locale; for my $s ( @{[ "_'nada_komo_el_'sol_", "_na'da_komo_el_so'l_" ]} ) { print $s; $s =~ s/(_)([^'][^_]+?)/$1'$2/g; print " : $s\n"; } __END__ C:\test>junk57 _'nada_komo_el_'sol_ : _'nada_'komo_'el_'sol_ _na'da_komo_el_so'l_ : _'na'da_'komo_'el_'so'l_

      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".
      In the absence of evidence, opinion is indistinguishable from prejudice.

        I think (mostly because I've only been following this thread from the sidelines) that this won't "work" if there is no underscore at the end of the string:

        #! /usr/bin/perl -w use strict; use locale; for my $s ( @{[ "_'nada_komo_el_'sol_", "_na'da_komo_el_so'l_", "_na'da_komo_el_sol" ]} ) { print $s; $s =~ s/(_)([^'][^_]+?)/$1'$2/g; print " : $s\n"; } __END__ > perl -w tmp.pl _'nada_komo_el_'sol_ : _'nada_'komo_'el_'sol_ _na'da_komo_el_so'l_ : _'na'da_'komo_'el_'so'l_ _na'da_komo_el_sol : _'na'da_'komo_'el_'sol

        My solution would be to use a zero-width lookahead to ensure but not match the following underscore:

        $s =~ s/(_)([^_']+?)(?=_)/$1'$2/g;

        ... but again, as I haven't been closely following, I'm not sure where my approach will fail the specifications.