my $code = qq( [head] Head text... [body] Body text... [something else] more text.. ); #example of text $code =~ s/\n//g; #remove all the newlines $code .= "\n"; #add one to the end $formatCode($code); sub formatCode{ my $str = $_[0]; $str =~ s#\[(.*?)\](.*?)(\[.*?\]|\n)#
##
$str =~ s#\[(.*?)\](.*?)(?=\[.*?\]|\n)#$2#ig;