my $file = 'myfile.txt'; my $txt = do { local (@ARGV, $/) = $file; <> }; $txt =~ s/[\r\n]/ /g; $txt =~ s/ /rand() < 0.5 ? q{ } : "\n"/eg; open(my $fh, '>', $file) or die "$0: Can't open $file for write: $!"; print $fh $txt; close $fh;