Missing some regexp knowledge

Once in a while I come across some topic that I should have learned a billion years ago. Something very basic and useful that I had a chance of seeing many times but haven’t, or probably had and ignored it. Today I found out that I was missing an important bit of Perl regexp knowledge. And you will probably laugh in my face when I’ll tell you.

Regular expression matching returns values as any other Perl function. The return value depends on the context. In scalar context, the value of 1 (true) is returned if there was a match. undef is returned if there was no match. Here is an example:

#!/usr/bin/perl -w
use strict;

my $line = 'this is my line';
my $result = $line =~ /is/;
print $result, "\n";

But the array context is more interesting. Actual matches are returned and can be used like so:

#!/usr/bin/perl -w
use strict;

my $line = 'this is my 123 line with 456 numbers';
my @result = $line =~ /.*?(\d+).*?(\d+).*/g;
print join("\n",@result), "\n";

What was I doing until now? Well, I was simply copying the data string into a temporary variable, and than removing everything that I didn’t need from that string. Obviously, that was one ugly and complex way of doing things. I wonder how did I went so far without finding it out.

2 thoughts on “Missing some regexp knowledge”

Leave a Comment