ashok has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I am trying to extract some directive filags in a build output file. I want to extract all the flags starting with -D and ending with a blank. For Ex:
cc -g -mcpu=800 -type -nostdinc -DFLAG1 -DFLAG2-float -fno-builtin cc -g -mcpu=800 -type -nostdinc -DFLAG1 -D_FLAG2 -fvolatile -fno-built +in -I
So my flags are -DFLAG1, -DFLAG2, -D_FLAG2. That means I pick all the flags and keep in an array where no flag repeats. For this my code is
#!/usr/local/bin/perl $file = shift @ARGV; chomp $file; open(BUILD,"$file") || die "File $file not found \n!"; @recs = <BUILD>; $count = 0; foreach(@recs) { $str = m/.\-D/; if ($str) { @flags = split(" ",$_); } foreach (@flags) { $str2 = m/^\-D/; if ($str2) { $finalflags[$count] = $_; $count++; } } } @sortflags = sort @finalflags; foreach(@sortflags) { print"$_\n"; }
But my problem is it finds repetition of flags. i.e -DFLAG1, -DFLAG2, -DFLAG!, -D_FLAG2. Finally I wrote a shell script like this:
rm out1.txt rm final.txt perl dir.pl > out1.txt #tells the flags repeated uniq -d out1.txt > final.txt #tells uniq flags uniq -u out1.txt >> final.txt
My all flags will be in final.txt which are -DFLAG1, -DFLAG2, -D_FLAG2. I know that this can be written in better manner. I tried to grep like:
if ($found = grep(/\b$_\b/,@finalflags) donot store inarray else store in array
But could not succeed. I know that code can be better than this. Can you pl. give your ideas? Thanks Ashok

Replies are listed 'Best First'.
Re: Regular Expression
by Fastolfe (Vicar) on Jan 13, 2001 at 05:40 UTC
    foreach (@recs) { $found{$1}++ while /\s-D(\S+)/g; } print "Found flags: ", join(" ", sort keys %found), "\n";
    Hashes are great for keeping track of unique values.
Re: Regular Expression
by I0 (Priest) on Jan 13, 2001 at 08:21 UTC
    @found{/(-D\S*)/g} = (); print "$_\n" for( sort keys %found );
      Great , it works for me. Thanks for your help.