#! perl -slw use strict; my $str = q[ first line #ifdef ABC second line conditional on ABC defined #else second line conditional on ABC not defined #endif #ifdef PQR second line conditional on PQR defined #else second line conditional on PQR not defined #endif third line ]; my $macro = 'ABC'; $str =~ s[ \#ifdef\s(\S+)\s+ ([^\n]+)\n \#else\s+ ([^\n]+)\n \#endif ]{ $1 eq $macro ? $2 : $3 }xeg or die 'No match'; print $str; __END__ C:\test>junk7 first line second line conditional on ABC defined second line conditional on PQR not defined third line