Start New Discussion within our Software Development Community

I thought it might be useful to show the special local matching variables that perl uses. Here they are:

$1..$9 Contains the subpattern from the corresponding set of parentheses in the last pattern matched like \1..\9
$& Contains the string matched by the last pattern match
$` The string preceding whatever was matched by the last pattern match, not counting patterns matched in nested blocks that have been exited already.
$' The string following whatever was matched by the last pattern match, not counting patterns matched in nested blockes that have been exited already.
$+ the last bracket matched by the last search pattern. This is useful if you don't know which of a set of alternative patterns matched.

If you want to know more about these and the global variables, like $_ and $/ go here:

http://www.kichwa.com/quik_ref/spec_variables.html

Thanks for the link Mike. One of my favourites is $. although I haven't managed to use it much yet. $. Is not a regex variable but here is an example of using it to identify the line numbers where a regex match succeeds.

#!/usr/bin/perl
use strict;
use warnings;

while (<DATA>){
    if (m/\bcane\b/){
        #The following statement uses the special variable $.
        #which contains the current line number of the input file
        print "Line number $. of the file contains the word $&.\n";
    }
}

__DATA__
The Spring blew trumpets of color;
Her Green sang in my brain --
I heard a blind man groping
"Tap -- tap" with his cane;

I pitied him in his blindness;
But can I boast, "I see"?
Perhaps there walks a spirit
Close by, who pities me, --

A spirit who hears me tapping
The five-sensed cane of mind
Amid such unguessed glories --
That I am worse than blind.

This prints the following:

Line number 4 of the file contains the word cane.
Line number 12 of the file contains the word cane.
This question has already been answered. Start a new discussion instead.