in reply to inserting new lines

You want to randomly change spaces into newlines? Something like:
s/ /rand() < .5 ? ' ' : "\n"/eg;
should do.

Replies are listed 'Best First'.
Re^2: inserting new lines
by Anonymous Monk on Apr 20, 2012 at 19:29 UTC
    nah trying to insert newlines after those 3 special characers, but decide what character to insert a newline after randomly, will it be after ';' or } or { ? would it be ; and { or just ; ?
      To randomly select one of the three characters, you can use code like my $char = qw(; { })[rand 3];. You can then interpolate the result into a substitution that uses a look behind.

      #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.

        well the code that was posted by the other member (or you?) was actually a better idea, only problem is that after running the script a few times the file becomes empty.
        #open file removing empty lines open(FILE, "<myfile.txt"); my $txt = do { local $/; <FILE>}; $txt =~ s/\n{3,}/\n\n/g; close FILE; #remove new lines $txt =~ s/\r|\n//g; #insert newlines after a randomly selected space $txt =~ s/ /rand() < .5 ? ' ' : "\n"/eg; open(FILE, ">myfile.txt"); print FILE; print FILE $txt; close FILE;
        this is fine, only problem is that after a few runs the file becomes empty.
        open(FILE, "<myfile.txt"); my $txt = do { local $/; <FILE>}; $txt =~ s/\n{3,}/\n\n/g; close FILE; $txt =~ s/\r|\n//g; $txt =~ s/ /rand() < .5 ? ' ' : "\n"/eg; open(FILE, ">myfile.txt"); print FILE; print FILE $txt; close FILE;