in reply to How to count number of multiple logical conditions used in if,elseif or while in perl
This code is of course not going to parse some arbitrary C code "while" statement lines(s)! It does appear to execute your test case as presented and I hope a starting point for you for further refinement. Of course this Perl code assumes that you have at least compilable C code.
Curiosity gets the better of me and I'm wondering what the application is? If it is some kind of code complexity measurement, perhaps the number of && and || operators would be more to what you want?
UPDATE: Made some small revisions to previous code. After seeing your post with an example and desired output.
older code is here, but not much different.#!/usr/bin/perl -w use strict; my $line; while ($line = <DATA>) { if ($line =~ m/\s*while/) { process_while(); next; } print $line; } sub process_while { #tweaked to allow the "(" after "while" to be on next line #or have blank lines before the "(" #that's for this for loop does find the first "(" line for ( ;$line !~ /\(/;(print $line),$line=(<DATA>)){} for (my $n_cndx =1; $line !~ m/\{/ ; $line=(<DATA>) ) { $line =~ s/(\w+)(\s*)(&&|\|\||\s*\)|\s*\n)/ $n_cndx++." $1$2$3" +/ge; print $line; } } =Prints: while ( ( 1 condition1 && 2 condition2 && 3 condition3 ) || ( 4 condition4 || 5 condition5 && 6 condition6 ) ) {more statements}; while(1 X){} =cut __DATA__ while ( ( condition1 && condition2 && condition3 ) || ( condition4 || condition5 && condition6 ) ) {more statements}; while(X){}
#!/usr/bin/perl -w use strict; my $line; while ($line = <DATA>) { if ($line =~ m/while\s*\(/) #perhaps m/^\s*while/ ? #think about "while in a comment". #other border cases... { process_while(); next; } print $line; } sub process_while { my $i =1; while (1) #normally while(1) not a good idea, but #I figure its ok here. { $line =~ s/(\w+)(\s*)(&&|\|\||\s*\))/ $i++." $1$2$3" /ge; print $line; return if $line =~ m/{/; $line = (<DATA>); } } =Prints: some statement; while( ( 1 condition1 && 2 condition2 && 3 condition3 ) || ( 4 condition4 || 5 condition5 && 6 condition6 ) { #statements; } while( ( 1 condition1 ) || ( 2 condition2 || 3 condition3 && 4 condition4 ) { #statements; } while( 1 condition1 && 2 condition2 || 3 condition3 ) { #statements; } more statements; =cut __DATA__ some statement; while( ( condition1 && condition2 && condition3 ) || ( condition4 || condition5 && condition6 ) { #statements; } while( ( condition1 ) || ( condition2 || condition3 && condition4 ) { #statements; } while( condition1 && condition2 || condition3 ) { #statements; } more statements;
|
|---|