Main Content

Running a piece of code is like drinking a pint of beer

Archive - Originally posted on "The Horse's Mouth" - 2009-06-11 19:04:53 - Graham Ellis

Q: What is the effect when I drink a pint of beer?

A: I get slightly tipsy.

But that's too simplistic!

A: The brewery has some more money
A: There's a glass to wash up
A: I need the loo!

Running a piece of code is like drinking a pint of beer - as well as a headline result, you get extra variables / side effects ... and the normal assignment statement (the = sign in all the languages we teach except Tcl) has a single target.

In Perl, though, side effect variables can be set too - and that's done especially with a regular expression match. The 'headline' return value is a true or false return, telling whether or not the string matched a patter, but there's more available to you if you want to use it:

, etc ... for 'interesting bits' that matched parts of the pattern
$`, $& and $' for the bits before and after the matched part and the match itself

And if you use a match in a list context, you'll get back a whole list of all the interesting bits ... matched many times over if you have used the "g" modifier on the match.

From today's course ... source code that shows lots of these extra variables