Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

Re: Perl Idioms Explained - @ary = $str =~ m/(stuff)/g

by Anonymous Monk
on Apr 07, 2015 at 15:42 UTC ( #1122712=note: print w/replies, xml ) Need Help??

in reply to Perl Idioms Explained - @ary = $str =~ m/(stuff)/g

So how do you check that the string contains only what you expect? For example you might have the following code
while ($str =~ s/\A(foo)//) { push @got, $1; } die "unexpected stuff in string: $str" if $str ne '';
This takes a paranoid approach, checking that there is no junk at the beginning of the string before the series of 'foo' begins, and no junk at the end. It would be more efficient to just say
@got = $str =~ m/(foo)/g;
but now you lose error checking. If $str contains 'xfooy' then the leading and trailing junk will be silently ignored. That's not great, since unmatched 'junk' more often than not indicates a bug in your regexp you need to fix. Is there a way to get the efficiency of m//g but still check that the whole string is matched? I suspect it will involve the \G anchor but I am not sure how.

Replies are listed 'Best First'.
Re^2: Perl Idioms Explained - @ary = $str =~ m/(stuff)/g
by ed (Initiate) on Apr 07, 2015 at 15:49 UTC
    I am the author of the above comment. Something like this seems to work:
    $result =~ /\A/g or die; # make extra sure we are at start of string @r = ($result =~ m/\G(foo)/gc); if ($result =~ /\G(.+)/sg) { warn "leftover junk at the end of result: $1"; }
    The key is the /c flag on the repeated match so that when it fails, it leaves the match position in place so the trailing junk, if any, can be reported. If there is leading junk, then the regexp won't match any times, and the whole string will be reported as 'leftover'. That is a good enough error message for my purposes.

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (4)
As of 2018-08-21 19:47 GMT
Find Nodes?
    Voting Booth?
    Asked to put a square peg in a round hole, I would:

    Results (203 votes). Check out past polls.