in reply to Return string that starts and ends with specific characters

#!/usr/bin/perl # http://perlmonks.org/?node_id=1164776 use strict; use warnings; my @answer; 'asdfgfhjkl' =~ /f.*j(?{push @answer, $&})^/; print "$_\n" for @answer;

Replies are listed 'Best First'.
Re^2: Return string that starts and ends with specific characters
by LanX (Saint) on Jun 02, 2016 at 16:53 UTC
    I had basically the same idea, but tried \0 to force the backtracking. (which didn't work)

    Why and how does ^ work?

    Cheers Rolf
    (addicted to the Perl Programming Language and ☆☆☆☆ :)
    Je suis Charlie!

      It works with (?=\0) so I'd say it comes from zero-width assertions preventing optimization.

      Edit : In this special case (single word without a j at the end) it also works with \b

        ... it also works with \b

        ... unless the string ends with the target character/pattern:

        c:\@Work\Perl\monks>perl -wMstrict -le "my @answer; 'asdfgfhjkljx' =~ /f.*j(?{push @answer, $&})\b/; print for @answer; " fgfhjklj fgfhj fhjklj fhj c:\@Work\Perl\monks>perl -wMstrict -le "my @answer; 'asdfgfhjklj' =~ /f.*j(?{push @answer, $&})\b/; print for @answer; " fgfhjklj
        Personally, I feel more comfortable using something that cannot possibly be true to force backtracking, like  (?!) or, from Perl 5.10 on,  (*FAIL) or  (*F) even though they take more keystrokes to type.

        Update: Oops... I missed "... this special case (single word without a j at the end) ..." in Eily's post; see Eily's reply below.


        Give a man a fish:  <%-{-{-{-<

        Cool. I picked it up from perl golf, and use ^ because it's shorter :)

      I think regex is smart enough to detect no \0 but not ^

        Yes regexes are optimized, if there is a leading or trailing string it's taken into consideration ( I'm to lazy to proof it with re deparse)

        but this looks like a fortunate bug, because ^ is a metacharacter in some positions, it's treated differently.

        Cheers Rolf
        (addicted to the Perl Programming Language and ☆☆☆☆ :)
        Je suis Charlie!