Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??
A /g RE in scalar context matches only once, starting from whatever pos() says it last finished at, and sets pos() of the variable appropriately. Its return is true iff it matched.

That is why my example used it in a looping construct. Otherwise you only get the first match.

BEGIN EDIT

I was asked exactly what that would look like. Here it is:

#!/usr/bin/perl -w use strict; while (<>) { my @pos; while (m/\s+/g) { # Loop while it matches push @pos, pos(); } print join " ", @pos; print "\n"; }
END EDIT

Note that this idea can be used to create rather complex parsing engines, each /g match being used to locate the next expected token that you are looking for. If you want to do this then you will need to be careful in how you pass the variable around. Specifically be aware of the fact that if pos($foo) is set then $bar=$foo does not result in pos($bar) being set. (But if you pass $foo into a function then pos($_[0]) will still be set.)

This is all explained in perlop. The return of a matching operation depends on whether you are in list or scalar context, and whether or not you have /g. All 4 combinations have different behaviour, and I have found occasion to use them all. :-)

Enjoy,
Ben


In reply to RE: (meonkeys: can't get every column) by tilly
in thread Locate char in a string by tilly

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (5)
As of 2021-09-23 11:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?