Home: Perl Programming Help: Regular Expressions:
Makefile regex

New User

Apr 11, 2011, 8:15 PM

Views: 7241
Makefile regex

Hi all,
I am having a little trouble trying to store data using regular expressions when reading in a Makefile.
The basic Makefile structure is:

Target : Prereq1 Prereq2 PrereqN

So what I am trying to do is store the Target into $tar, the Prereqs into @pre and the command string into $com. I am able to get the Target : Prereq to split around the colon, but that doesn't help if there are multiple prereqs because it will just store them all as one string into the array. How would I do a regex that tells it to take every word before/after the colon or if the line begins with a tab, as the command line is. Any help would be appreciated. I have been struggling with this for a couple hours now. Thanks!


Apr 11, 2011, 9:23 PM

Views: 7239
Re: [smjenkin] Makefile regex


Not sure what you mean by lines that begin with tabs, but if you can split a string into target + prereqs up, then you can take the prereqs and split it up further using the same method e.g. in 1 regex:

use strict;
use warnings;

my $string = "Target : Prereq1 Prereq2 PrereqN";
my ($tar, @pre) = split /\s:\s|\s/, $string;

print "$tar\n";
print "$_\n" foreach (@pre);


(This post was edited by Zhris on Apr 11, 2011, 9:29 PM)


Apr 28, 2011, 3:58 AM

Views: 7108
Re: [Zhris] Makefile regex

Not sure what you mean by lines that begin with tabs

Makefiles adhere to the weird syntax, that a tab character in the beginning of a line (\t) has a special meaning. In particular, the meaning is different from a space character.


Apr 28, 2011, 4:11 AM

Views: 7107
Re: [smjenkin] Makefile regex

You can find out whether it is a command line by testing

substr($line,0,1) eq "\t"

This basically leaves you with the prerequisite lines (actually, you have also to care about empty lines, lines containing variable definitions, and comments, but you didn't ask about them, so I guess you know how to handle them).

For the target lines, you could do a


to get at the individual fields. The first item should be the target, the other ones are the prereqs.