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

Hi

I have a rather simple question: after loading an entire file into a string (with file slurp), I want to substitute all expressions of type func1(x, "text %f and %f...", "hello") for the exception of some of the type func1(x, "%f", "hello"). I'm trying $data =~ s/func1(x, \"[^%](.*)/text/gi; But some of the first type are not being substituted (I think because of the wrong place of [^%]. Any help is apreciated.

Kind regards, Kepler

Replies are listed 'Best First'.
Re: Substitute strings
by Athanasius (Archbishop) on Sep 12, 2016 at 09:30 UTC

    Hello kepler,

    Is this what you’re looking for?

    use strict; use warnings; my $data = 'func1(x, "%f", "hello")'; $data =~ s/ ( func1 \( x, \s \" ) % (.) "/$1text %$2 and %$2..."/ix; print ">$data<\n";

    Output:

    19:23 >perl 1694_SoPW.pl >func1(x, "text %f and %f...", "hello")< 19:23 >

    Note that you have to escape the left parenthesis surrounding the function arguments, otherwise it will be interpreted as part of a grouping construct, and you’ll get Unmatched ( in regex;... warnings.

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

      Hi,

      Great solutions guys!!!

      Thanks....

      Kepler

Re: Substitute strings
by marto (Cardinal) on Sep 12, 2016 at 09:12 UTC

      I'm sorry...

      What I'm trying is $data =~ s/func1(x, \"[^%](.*)/text/gi;
        I'm sorry...

        Sorry is good, but even better would be to go back and fix the formatting problem in your OP so the janitors don't have to be lumbered with it. Please see the Edit link in the node.


        Give a man a fish:  <%-{-{-{-<

Re: Substitute strings
by clueless newbie (Curate) on Sep 12, 2016 at 12:20 UTC
    I assume that you're interested in func1 followed by balanced parenthesis so this might be of use.
    #!/usr/bin/env perl use strict; use warnings; my $balpar_re=qr/ ( \( # opening ( (?:[^'"()]++ # Not a ', ", ( or ) - no b +acktracking |(?:'(?:[^']|\')*?') #' a single quote string |(?:"(?:[^"]|\")*?") #" a double quote string |(?-1) # must be a ( or ) so recur +se )*+ # zero or more time - no ba +cktracking \) # closing ) ) /x; my $text=<<'__EOT__'; xfunc1("shouldn't be changed!") func1 (abc,"abc","should,be,changed!"); func1(arg(),narg()); __EOT__ if ($text=~ s{\bfunc1\s*$balpar_re}{newtext}g) { print $text; }; __DATA__
          |(?-1)                         # must be a ( or ) so recurse

      kepler: Please note that the  (?-PARNO) regex operator is only available with Perl version 5.10 and above. Please see Extended Patterns in perlre.


      Give a man a fish:  <%-{-{-{-<