Perl match in scalar and list context (regex)

Sometimes it takes a throw-away comment in a book for a whole stack of jumbled info to just slot into place. The ‘Sixth Sense’ is on the telly and my wife is asking why she ‘didn’t notice it’ (the fact that nobody talks to Bruce Willis thought the film aside from the boy), well its the same with me and the =~ match operator in scalar and list context! Until somebody points out the obvious, we don’t notice it. That was a stretch i know, but just go with it for now! Here’s the opening script:

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

my $string = "the quick brown fox jumped over the lazy dog";
my $find_the_fox = $string =~ /\s+([a-z][a-z]x)\s+/;
print "$find_the_fox\n";

When we execute this we get the following output:

1

Which I always found disappointing, i wanted the word ‘fox’ to appear. The reason is that in scalar context we just get the number of matches. To get the list context, we need to add some brackets round the $find_the_fox as so:

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

my $string = "the quick brown fox jumped over the lazy dog";
my ($find_the_fox) = $string =~ /\s+([a-z][a-z]x)\s+/;
print "$find_the_fox\n";

and hey presto, we get:

fox

Hope that helps

This entry was posted in Perl and tagged , , , . Bookmark the permalink.

Leave a Reply