my $new_text = $node->textContent() x shift(@counts); $node->removeChild($_) for $node->findnodes('text()'); $node->appendText($new_text);