modifying the haystack string inside while($haystack =~ /needle/g) {... }

Discussion in 'Perl Misc' started by Yakov, Aug 10, 2008.

  1. Yakov

    Yakov Guest

    What exactly happens if I modify the $haystack inside such while (see
    subject) ?

    I realize that "don't do this" is good answer, and , but still, I am
    cusious
    know what happens if $haystack is modified (nobody does it
    conciensly).

    I see two-three possibilities
    (1) matching position is reset to 0
    (2) matching position remains where it was.
    (3) next match is forced to fail
    .... (4) warning is printed ... (5) program dies

    Just curious
    Y.L.
     
    Yakov, Aug 10, 2008
    #1
    1. Advertisements

  2. Yakov

    Ben Bullock Guest

    It would be easier to reply to your message if you didn't put part of
    it into the subject like that.

    Anyway, "while" just tests for true or false, so of course you can change
    $haystack as much as you like inside the loop.
     
    Ben Bullock, Aug 10, 2008
    #2
    1. Advertisements

  3. Code from subject [please don't put it there]:

    while($haystack =~ /needle/g) { ... }

    It's fine to modify the variable in a while loop. In your case, it would
    reset the match.

    my $s = 'abc';

    while ($s =~ /(\w)/g) {
    print "$1\n";
    $s = 'xyz' if $1 eq 'b';
    }
    __END__
    a
    b
    x
    y
    z

    There are caveats about modifying an array/list/hash while iterating
    over it, but those don't apply here.

    -mjc
     
    Michael Carman, Aug 10, 2008
    #3
  4. Yakov

    jl_post Guest

    You're referring to: while($haystack =~ /needle/g) { ... }

    This actually happened to me once. I had to traverse a set of
    messages in a string and modify one byte (character) in each message.
    However, I discovered that whenever I modified the variable ($haystack
    in your case), its pos() would reset to zero and the regular
    expression would start matching from the beginning.

    To work around that behavior, once I located the byte/character to
    change I saved off the pos() value, changed the byte of the message,
    and then restored the pos() value of the string, like this:

    while ( $haystack =~ m/ ... /g )
    {
     
    jl_post, Aug 14, 2008
    #4
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.