Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

RE: How do I remove blank lines from text files?

by Russ (Deacon)
on Jul 10, 2000 at 19:16 UTC ( #21854=note: print w/replies, xml ) Need Help??


in reply to How do I remove blank lines from text files?

Update: as davorg correctly points out, I had a strange and (mostly) unnecessary construct. This is my updated version.

As an explanation: I had the <IN> in a while loop, to take advantage of the diamond operator's auto-assign-to-$_ feature. This code just makes the assignment explicit.

Thanks, davorg!

This will write a new file with blank lines (where there are two or more newlines together) removed:

local $/ = undef; open IN, "<junk" or die "Couldn't open junk: $!"; open OUT, ">fixed" or die "Couldn't open fixed: $!"; ($_ = <IN>) =~ s/\n{2,}/\n/g; print OUT; close IN; close OUT;
Variations on this theme (like whitespace, as noted elsewhere in this thread) would be similar...

Russ

Replies are listed 'Best First'.
RE: RE: How do I remove blank lines from text files?
by perlmonkey (Hermit) on Jul 11, 2000 at 04:29 UTC
    Just to nitpick a tiny bit, I want to warn about your modification to $/.

    By doing things the way to did, you are setting yourself up for crazy-ass bugs. You properly localize the variable, but the scope of the localization is way too broad.

    I suggest getting in the habit of anonymous blocks every time you localize a global variable. Like This:
    open OUT, ">fixed" or die "Couldn't open fixed: $!"; open IN, "<junk" or die "Couldn't open junk: $!"; { local $/ = undef; ($_ = <IN>) =~ s/\n{2,}/\n/g; print OUT; } close IN; close OUT;
    This way you properly limit the scope of local $/ to just the lines you need it. And wont accidentilly screw yourself up later.
      Good point. I should have included that in my snippet.

      Russ
      Brainbench 'Most Valuable Professional' for Perl

RE: RE: How do I remove blank lines from text files?
by davorg (Chancellor) on Jul 10, 2000 at 19:32 UTC

    As you've undefined $/ and are therefore acting in 'slurp' mode, you'll read the whole file in with your first call to <IN>. Doesn't that make your while loop unecessary?

    --
    <http://www.dave.org.uk>

    European Perl Conference - Sept 22/24 2000, ICA, London
    <http://www.yapc.org/Europe/>

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (5)
As of 2020-10-21 07:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My favourite web site is:












    Results (212 votes). Check out past polls.

    Notices?