Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re^5: perl indication of end of string already matched

by AnomalousMonk (Archbishop)
on Jun 09, 2020 at 00:40 UTC ( [id://11117845]=note: print w/replies, xml ) Need Help??


in reply to Re^4: perl indication of end of string already matched
in thread perl indication of end of string already matched

BTW: Another way to determine the start/middle/end position of a matched substring in a string is by using the  @- @+ regex special variables; see perlvar.

c:\@Work\Perl\monks>perl -wMstrict -le "my $s = 'foo--bar--baz'; ;; while ($s =~ m{ (\w+) }xmsg) { printf qq{matched '$1' %s of '$s' \n}, $-[1] == 0 ? 'at start' : $+[1] == length $s ? 'at very end' : 'in middle'; } " matched 'foo' at start of 'foo--bar--baz' matched 'bar' in middle of 'foo--bar--baz' matched 'baz' at very end of 'foo--bar--baz'
Play with adding '-'s at the start/end of  $s to convince yourself this works.


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

Replies are listed 'Best First'.
Re^6: perl indication of end of string already matched (updated)
by haukex (Archbishop) on Jun 09, 2020 at 08:29 UTC

    Good point, although in this case those variables also don't allow one to differentiate between the last two matches:

    $ perl -MData::Dump -e '$a="abc";for(1..6){ $a=~m/.|$/g; dd \@-,\@+ }' ([0], [1]) ([1], [2]) ([2], [3]) ([3], [3]) ([3], [3]) ([0], [1])

    Update: Hmm, well they can if one adds capture groups, which is kind of the same workaround as I showed here.

    $ perl -MData::Dump -e '$a="abc";for(1..6){$a=~m/(.|$)/g; dd \@-,\@+}' ([0, 0], [1, 1]) ([1, 1], [2, 2]) ([2, 2], [3, 3]) ([3, 3], [3, 3]) ([3], [3, 3]) ([0, 0], [1, 1])

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11117845]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (6)
As of 2024-03-28 08:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found