use strict; undef $/;#In order to read the whole file at once open(F,"test.txt") or die $!; my $slurpedfile = ; close F; my @matches = $slurpedfile =~ m{ ( /\* .*? \*/) | ( \/\/[^\n]*) | " (?: [^"\\]* | \\. )* " | ' (?: [^'\\]* | \\. )* ' | . [^/"']* }xgs; @matches = grep {defined $_} @matches; #get rid of undefs my $linenum = 1; foreach my $match (@matches) { $slurpedfile =~ /\Q$match/; my $before = $`; $slurpedfile = $'; $linenum += $before =~ tr/\n/\n/; foreach (split "\n", $match) { print "Line $linenum\t$_\n"; $linenum++; } $linenum--; # the foreach above adds one too many } __OUTPUT__ Line 2 //Hello Line 3 // single line c++ comment Line 5 /* single line c comment */ Line 6 /* Line 7 multi line Line 8 c style comment */ Line 10 // another single line c++ comment