Ad-vic
Ad-vic

Reputation: 529

single line comment to be excluded

I am writing Perl script to execute on C code I want to exclude my code from running inside comments(/* and */)

$flag = 0;
while(<>){

if($_ =~ /\/\*/ ){
    $flag = 1; 
    }

if($_ =~ /\*\//){
   $flag = 0;
    }

if($flag == 0) {
    execute other code
    }
}

This works fine for multiline comments like

/*
  ...
  ...
*/

but doesn't work for single line comment like

/* this is an example 123 */

need help on regex command to exclude everything(characters, integers, special characters) between " /* " and " */ "

Upvotes: 0

Views: 58

Answers (2)

KeyNone
KeyNone

Reputation: 9180

Imagine what happens when your program encounters a single-line-comment (/* comment */):

  1. It sees: /* so it sets flag = 1
  2. It sees: */ so it sets flag = 0 immediately afterwards
  3. Flag is 0, so it executes your "other code"

Try altering the order of your if-statements:

$flag = 0;
while(<>){

if($_ =~ /\/\*/ ){
    $flag = 1; 
    }

if($flag == 0) {
    execute other code
    }

if($_ =~ /\*\//){
   $flag = 0;
    }    
}

This way you first check if your line contains /* and in dependence to this you "execute other code" (better to say: in this case you don't execute it). Afterwards you reset your flag if there is a */ on the same line.

Upvotes: 2

Vijay
Vijay

Reputation: 67291

You can simply add one more statement inisde while loop as the first statement inside it like

$_=~s/\/\*.*?\*\///g;

Upvotes: 0

Related Questions