Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

weird problem

by Anonymous Monk
on Apr 20, 2012 at 20:50 UTC ( #966257=perlquestion: print w/ replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi, i posted about inserting new lines from a text file, so sorry about this new topic but i screwed up my last one :/ will try not to do this again.. so anyway im not sure why but after running this script a few times my 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;

Comment on weird problem
Download Code
Re: weird problem
by Riales (Hermit) on Apr 20, 2012 at 21:09 UTC

    Why do you do this:

    $txt =~ s/\n{3,}/\n\n/g;

    When you're going to do this anyways:

    $txt =~ s/\r|\n//g;

    ?

    Also, I don't think you need that first print FILE;

    Also, try adding or die $! after your open calls.

      I tried what you suggested, although it's neater it doesnt solve the problem..
Re: weird problem
by Anonymous Monk on Apr 20, 2012 at 22:49 UTC
    This works just fine:
    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;
      doesnt eventually empty the file, but it only works 2-3 times before it will no longer modify the text in the file. to be able to modify the text, when reading the file all lines must be restored (remove empty lines) and then repeat the process of adding newlines in randomly selected spaces.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://966257]
Approved by ww
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (6)
As of 2014-10-25 11:25 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (143 votes), past polls