The global modifier in Perl’s regular expressions.

Just this afternoon, I had the occasion to think up of a quick regular expression to match some numbers in a fixed string within a large block of string. The regular expression didn’t take long to figure out. However, after testing it against the block of string, it became obvious that the string had multiple substrings that matched the regular expression pattern and that all the matches were required. Now, if I were doing this in Python, I would without thinking use to apply the pattern across the string (or the other way round) and use the groups() method to retrieve all the matched groups. In Perl, despite having spent thrice as much time coding in than in Python, I didn’t know what to do. I tried looping around the match expression, but that didn’t quite work as I wanted it to. It was then, when haplessly groping for some sort of help, I opened perldoc perlrequick. It is a Quick Tutorial on Regular Expressions In Perl that comes bundled with the Perl distribution. The section on “More Matching” in that tutorial introduced the use of the global modifier “///g”. Now, I had known of the global modifier but I didn’t know how to use it in the context of multiple group matches.

I had to match the pattern\d+) multiple times. Using the global modifier it can be achieved thusly:

my @bid = ($alert =~ m#\d+)#g);


One thought on “The global modifier in Perl’s regular expressions.

  1. There is a subtle thing to be noted here. In scalar context, “$alert =~ m#\d+)#g” returns either True or False. In list context, however, like it is used in the post, it returns the individual substrings matched.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s