Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

Re: removing blank lines from files

by zakb (Pilgrim)
on Jun 20, 2002 at 12:44 UTC ( #175987=note: print w/replies, xml ) Need Help??

in reply to removing blank lines from files

Perhaps those "blank" lines contain spaces? Also, using chomp simply removes line endings (e.g. carriage return), it won't skip to the next line. You haven't really shown us your code, but presumably you need something like:

#!/usr/bin/perl -w use strict; while (<>) { # loop to next line if it contains whitespace only next if /^\s+$/; print; }

Update: Tested with files with blank lines consisting of just \n and blank lines with spaces; works in both cases; \s+ matches end-of-line characters, see perlretut (query from mirod & busunsl).

Replies are listed 'Best First'.
Re: Re: removing blank lines from files
by busunsl (Vicar) on Jun 20, 2002 at 12:49 UTC
    next if /^\s+$/;
    next if /^\s*$/;
    and it will catch empty lines and lines containing only whitespace.

      Actually Perl DWIMs properly here, and /^\s+$/ catches empty lines. The $ is quite magic, if the \n at the end of the string/line is matched then $ matches the empty end-of-string, if the \n is not matched then $ matches it, plus the end-of-string.

      You can test it with this code:

      my $string="12\n"; print 'matches ^\d+\n$' . "\n" if( $string=~ /^\d+\n$/); print 'matches ^\d+$' . "\n" if( $string=~ /^\d+$/);

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (2)
As of 2022-08-18 04:18 GMT
Find Nodes?
    Voting Booth?

    No recent polls found