chrisbarton has asked for the wisdom of the Perl Monks concerning the following question:

I am trying to remove lines from a file that are just carrige returns. I've tried the code below but this doesn't work - I'm sure this is pretty simple.

while ($requests = <REQUESTS>) { if ($requests ne '\n') { print MAIL "$requests"; } }

Replies are listed 'Best First'.
Re: removing carriage returns
by RMGir (Prior) on Mar 29, 2002 at 14:25 UTC
    You came _this_ close to getting it right :)
    while ($requests = <REQUESTS>) { if ($requests ne "\n") { print MAIL "$requests"; } }
    The problem is that single quotes don't convert things like \n, so you were printing everything except lines that contain a literal \, followed by a literal n.

    In the "there's more than one way to do it" tradition, you could just use the grep command.

    print MAIL grep !/^$/,<REQUESTS>;
    The "empty line" regular expression will work because $ will match just before the \n.

    You could also write your code using the "suffix" form of the condition.

    while ($requests = <REQUESTS>) { print MAIL $requests if $requests ne "\n"; }
    or
    while ($requests = <REQUESTS>) { print MAIL $requests unless $requests=~/^$/; }
    Hope this helps!
    --
    Mike (Edit: had fouled up the grep example)
Re: removing carriage returns
by Parham (Friar) on Mar 29, 2002 at 15:11 UTC
    also (it's easier to understand, but you adding more code), just an alternative...
    while ($requests = <REQUESTS>) { chomp $requests; #remove any endline characters if ($requests ne "") { #if all endline characters are wiped, check f +or nothingness print MAIL "$requests\n"; } }
    EDIT. RMGir got me good. Sorry for the mistake. (didn't put my newlines back in)
      Don't forget to put the newline back in, though...
      while ($requests = <REQUESTS>) { chomp $requests; #remove any endline characters #if all endline characters are wiped, #check for nothingness if ($requests ne "") { # add newline for lines we're printing print MAIL "$requests\n"; } }

      --
      Mike
Re: removing carriage returns
by Juerd (Abbot) on Mar 29, 2002 at 19:29 UTC

    Carriage Return is \015.
    \n is \012, \015 or \015\012.
    \012 is Line Feed.

    U28geW91IGNhbiBhbGwgcm90MTMgY
    W5kIHBhY2soKS4gQnV0IGRvIHlvdS
    ByZWNvZ25pc2UgQmFzZTY0IHdoZW4
    geW91IHNlZSBpdD8gIC0tIEp1ZXJk