The Match Operator m//g in List Context and pos($)

Acquiring a set of patterns out of a string

Problem: recover the file and the variable bindings out of a syntax that looks like


Reference: perlrequick –

More matching

There are a few more things you might want to know about matching operators. The global modifier //g allows the matching operator to match within a string as many times as possible. In scalar context, successive matches against a string will have //g jump from match to match, keeping track of position in the string as it goes along. You can get or set the position with the pos() function. For example,

$x = "cat dog house"; # 3 words
while ($x =~ /(w+)/g) {
    print "Word is $1, ends at position ", pos $x, "n";


  1. Word is cat, ends at position 3
  2. Word is dog, ends at position 7
  3. Word is house, ends at position 13

A failed match or changing the target string resets the position. If you don’t want the position reset after failure to match, add the //c , as in /regex/gc .

In list context, //g returns a list of matched groupings, or if there are no groupings, a list of matches to the whole regex. So

@words = ($x =~ /(w+)/g);
  1. matches,
  2. $word[0] = 'cat'
  3. $word[1] = 'dog'
  4. $word[2] = 'house'