Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

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;

Replies are listed 'Best First'.
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.
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..

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://966257]
Approved by ww
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (5)
As of 2018-06-25 01:18 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (126 votes). Check out past polls.