in reply to Junking excess string.. junk with s///.

First, a link. Read about how regexp's are greedy.

Keeping that in mind, what your first example does is match as much as it can until it finds the last \n. Since you have anchored it to the beginning of your string, it starts at the beginning if your strings, and puts everything until the last \n into $1.

AIUI, the second piece of code does the following:

  1. Find the first \n in your string.
  2. Grab everything after it.
  3. Junk it
  4. Assign the altered string (which is everything before the first \n) back to $val.

Update: OK, so I don't quite understand regexp's like I thought I did (and I wasn't even willing to give myself that much credit!) I sit corrected; thanks sauoq. Thank you, drive through.

  • Comment on Re: Junking excess string.. junk with s///.

Replies are listed 'Best First'.
Re: Re: Junking excess string.. junk with s///.
by sauoq (Abbot) on Oct 16, 2003 at 06:09 UTC
    Keeping that in mind, what your first example does is match as much as it can until it finds the last \n.

    That is incorrect. The dot (".") does not match a newline.¹ Therefore, /^(.*)/ will capture everything up to the first newline, not the last one.

    1. Unless the regex is modified with /s. The OP's was not.

    -sauoq
    "My two cents aren't worth a dime.";
    
Re: Re: Junking excess string.. junk with s///.
by SavannahLion (Pilgrim) on Oct 16, 2003 at 06:22 UTC
    So . matches \n as well?

    What's really strange is that, so far, everyone seems to be making sense here. :(

    If you say that Regex's are greedy by stopping at the last \n and someone above you says that it stops at the first \n (as in foo\nbar\n becomes foobar\n) how do I know which way the Regex is behaving?

    Is it fair to stick a link to my site here?

    Thanks for you patience.

      Listen to everyone else. I did some further reading and was corrected by others, and have found myself to be wrong. Sorry for the confusion.