$s ='25 {fred and barney} text 2.36 12.0 {bam bam} text {pebbles}'; $s =~ s[(\{.*?\})]{ local $_=$1; tr[ ][_]; $_}ge; print $s; 25 {fred_and_barney} text 2.36 12.0 {bam_bam} text {pebbles}