Multiple Variable Assignments with Perl's Binding Operator

| No Comments | Bookmark and Share

I learned something new in the world of Perl regular expressions today when I came across this line:

 my ($foo, $bar, $baz) = $string =~ /(.oo)(.*?r)(.*?z)/;

The operative side of the line, $string =~ /(.oo)(.*?r)(.*?z)/ is a normal Perl regex binding statement - apply the regular expression /(.oo)(.*?r)(.*?z)/ to $string. What's interesting is that the binding operator returns the things matched within the capturing parenthesis as an array, allowing you to assign them all at once, as demonstrated by the left hand side of that = expression. The above statement does the same as the more verbose:

$string =~ /(.oo)(.*?r)(.*?z)/;
my ($foo, $bar, $baz) = ($1, $2, $3);

Used in a scalar context along with the /g modifier, this is an easy way to count count occurences:

my $count = $string =~ m/\./g;

Leave a comment

About this Entry

This page contains a single entry by Drew Stephens published on April 18, 2008 8:29 AM.

Taqueria Pancho Villa was the previous entry in this blog.

Auto-remove Old Items from The Trash in Mac OS X is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.

Powered by Movable Type 5.1