in reply to Using Look-ahead and Look-behind

Returning to this example below…

s/(?<=look)(?=ahead)/-/g;

…assume “look” and “ahead” are on separate lines one below the other. Then the line becomes this…

s/(?<=look)\n(?=ahead)/-/g;

Is there some restriction, as the two words do not get joined with a dash? (At least for me)

Plus, there is no error message; the command just doesn’t work. My one-liner is below. I’ve ensured my apostrophe’s are correct after I copy/paste; plus, I’ve key-stroked every character, and tried numerous variations, etc., etc. Using Mac OS Sequoia 15.0 and perl 5.34.

perl -i -pe ’s/(?<=look)\n(?=ahead)/-/g;’ myfile.txt

Replies are listed 'Best First'.
Re^2: Using Look-ahead and Look-behind
by Corion (Patriarch) on Nov 28, 2024 at 06:18 UTC

    You're reading your input line-by-line but you're trying to match across lines. That won't work.

    The following should work, reading the input all at once (see perlrun):

    perl -g -i -pe ’s/(?<=look)\n(?=ahead)/-/g;’ myfile.txt

      Thank you very, very much for setting me on the right path! While (in my environment) the -g switch isn't allowed for (what I learned to be was) slurping, instead using the -0777 switch did work nicely. I had seen this switch before, but until now wasn't aware of its usage until I dug deeper, prompted by your input.

      I was stuck on this for a long time - thanks again for the quick response!

      P.S. I just found where version 5.36 would allow the use of the -g switch, which is apparently a shortcut for using -0777.

        The -g only came in with perl 5.36 so won't be available in many LTS platforms unless they backport it. Using -0777 as you have mentioned is perfectly fine and, AFAIAA, will continue to be.


        🦛