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

I am trying to swap everything within the first set of quotes from "this first quote" to "that" without changing the text within the second set of quotes. Anybody know how? Seems to me like it should be a fairly basic single-line =~ s/// command, but I can't get it.
So

$text = "Test of \"this first quote.\" Second quote \"ignored.\"";

Should become

$text = "Test of \"that.\" Second quote \"ignored.\"";

Replies are listed 'Best First'.
Re: Swap between first found match
by leira (Monk) on Mar 04, 2004 at 01:34 UTC
    If you give us a snippet of code to tell us what you've tried, and explain how it didn't work the way you expected, it will be easier for us to understand where you might be stumped.

    However, I think you might be looking for something like this:

    my $text = "Test of \"this first quote.\" Second quote \"ignored.\""; $text =~ s/\"(.*?)\"/\"that\"/;

    Linda

    Update: I responded quickly, and could/should have been much clearer. Let's try that again.

    my $text = 'Test of "this first quote." Second quote "ignored."'; $text =~ s/"(.*?)"/"that"/;
Re: Swap between first found match
by dragonchild (Archbishop) on Mar 04, 2004 at 01:31 UTC
    s/// does first match only by default. $text =~ s/"this first quote"/"that"/; should do it.

    Also, I'd write your assignment as $text = qq{Test of "this first quote." Second quote "ignored."}; Less backslashing with the same interpolation..

    ------
    We are the carpenters and bricklayers of the Information Age.

    Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.

Re: Swap between first found match
by pzbagel (Chaplain) on Mar 04, 2004 at 01:34 UTC

    If you just want to change the first instance on a given line, then it is just a s/// command but don't use the g modifier.

    s/"[^"]*"/"that"/;
      Use non-greedy match:  .*?
      s/".*?"/"that"/;

        What's wrong with a negated character class? [^"]