#!/usr/bin/perl -w use strict; my $line; while ($line = ) { 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=()){} for (my $n_cndx =1; $line !~ m/\{/ ; $line=() ) { $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){}