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