Groups in Regular Expressions: Learn Perl By Doing It, Part 8

Groups in regular expressions allow you to pick out particular parts of the data you're matching that you can then refer to again later. For example, you can extract just a machine ID from a complex machine specification text, or all the words beginning with "d" from your essay, or whatever.



 
use strict;
use warnings;

$|=1;

sub main {
    my $file = 'C:tutorialperlmymanjeeves.txt';
    
    open(INPUT, $file) or die("Input file $file not found.n");
    
    while(my $line = <INPUT>) {

        # Surround the bits you want to "capture" with round brackets
        if($line =~ /(I..a.)(...)/) {
            # The stuff matched by the first set of round brackets if now in $1
            # The stuff matched by the second set is in $2
            print "First match: '$1'; second match:'$2'n";
        }
    }

    close(INPUT);
}

main();