use 5.014; my $s = "a (d (b) (e (f) ) ) c"; say remove_par($s); sub remove_par { my ( $result, $open ); foreach my $ch ( split // => shift ) { $open++ if $ch eq '('; $open-- if $ch eq ')'; $result .= $ch if !$open && $ch ne ')'; } die "non-matching parentheses" if $open; return $result; };