Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: New Line at End File

by sauoq (Abbot)
on Dec 09, 2002 at 23:43 UTC ( [id://218690]=note: print w/replies, xml ) Need Help??


in reply to New Line at End File

Here's a way to do it without reading the whole file in first...

#!/usr/bin/perl use strict; use Fcntl qw(SEEK_END SEEK_CUR); my $f = shift; open F, "+<", $f or die "Couldn't open $f: $!\n"; seek F, -1, SEEK_END; seek F, -2, SEEK_CUR while (getc(F) eq "\n"); truncate F, tell F;
-sauoq
"My two cents aren't worth a dime.";

Replies are listed 'Best First'.
Re: Re: New Line at End File
by BrowserUk (Patriarch) on Dec 10, 2002 at 05:10 UTC

    It's nit time:^) The only question is the nit the code or me but...

    Doesn't the use of -2, make this non-portable? Wouldn't this only work on DOSish systems? How about -length "\n" instead of -2?


    Okay you lot, get your wings on the left, halos on the right. It's one size fits all, and "No!", you can't have a different color.
    Pick up your cloud down the end and "Yes" if you get allocated a grey one they are a bit damp under foot, but someone has to get them.
    Get used to the wings fast cos its an 8 hour day...unless the Govenor calls for a cyclone or hurricane, in which case 16 hour shifts are mandatory.
    Just be grateful that you arrived just as the tornado season finished. Them buggers are real work.

      The only question is the nit the code or me but...

      Personally, I think that nit should be with the "OS"... but, yeah. You got me. ;-)

      -sauoq
      "My two cents aren't worth a dime.";
      
Re: Re: New Line at End File
by jmcnamara (Monsignor) on Dec 10, 2002 at 11:29 UTC

    This also strips the last newline from the file.

    Changing the last line to the following should fix it:

    my $pos = tell F; truncate F, 1 +$pos if $pos > 1;

    --
    John.

      This also strips the last newline from the file.

      Of course it does. That's exactly what was asked for. The OP read, "Is there an easy way to determine if there are new line characters at the bottom of a file, and if so delete them?" He didn't ask how to delete all but one newline or how to remove blank lines.

      -sauoq
      "My two cents aren't worth a dime.";
      

        You are right. I stand corrected.

        --
        John.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (5)
As of 2024-03-28 12:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found