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

I've used the s/// operator with great success before. However, this time I'm getting some weird results.


I have this:

$test = "mouse_eatsCat_andDog.txt"; $test =~ s/"_(.+)"/$1/; #because I want to get "eatsCat_andDog.txt" print "$test"; #result is "mouse_eatsCat_andDog.txt"

I'm very puzzled by this! I've tried this with no success as well:

$test =~ s/"^mouse_(.+)"/$1/;

I made it work using a different method so that I got only "eatsCat_andDog.txt" but I want to know why the above method doesn't work. Thanks!

Replies are listed 'Best First'.
Re: s/// operator
by BrowserUk (Patriarch) on Nov 19, 2015 at 19:22 UTC
    $test = "mouse_eatsCat_andDog.txt"; $test =~ s/"_(.+)"/$1/; #because I want to get "eatsCat_andDog.txt"

    Your string doesn't contain a quote(") followed by an underscore(_), so your regex never matches.


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    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". I knew I was on the right track :)
    In the absence of evidence, opinion is indistinguishable from prejudice.

      OMG!!! The dumbest mistake ever! Thank you very much!

Re: s/// operator
by stevieb (Canon) on Nov 19, 2015 at 19:26 UTC

    The latter regex $test =~ s/"^mouse_(.+)"/$1/; is very close. The problem is that when you assign a string to a variable (eg: $test = "blah";), the quotes are stripped off. So it's the double-quote at the beginning of the regex that is breaking things. To further, ^ denotes the beginning of the string, so the " would never match even if there was one embedded in the string. Note though that the second double-quote at the end of the regex will allow the regex to match even though there isn't one in the string, because you capture everything (.+) up to it.

    This works:

    $test =~ s/^mouse_(.+)/$1/;

      Thank you! That was it :)

Re: s/// operator
by GotToBTru (Prior) on Nov 19, 2015 at 19:26 UTC

    Your s/// is not finding any matches to change. "_, for one example, never occurs in your string.

    Dum Spiro Spero