How do I add lines to the top and bottom of a file in Perl?

后端 未结 9 1133
自闭症患者
自闭症患者 2021-01-06 23:38

I want to add a line to top and bottom of the file. I can do it following way.

open (DATA, \"

        
相关标签:
9条回答
  • 2021-01-06 23:57

    I don't really speak Perl, but perhaps this works for some situations:

    perl -0777 -pi -e 's/^/MY TEXT TO PREPEND/' myfile.txt
    

    That is, open the file in paragraph mode (one line), and replace the start of that line with your new text, doing an in-place rewrite.

    Probably not efficient for many large files.

    0 讨论(0)
  • 2021-01-07 00:02

    Perl can't insert at the beginning of a file because few operating systems allow that. You need a rewrite operation of the type you have here.

    One possible problem you may have with that code is with truly large files that can't fit in your address space.

    By reading the entire file in then writing it out, you may run into memory problems. What I would have done would be to:

    • rename the current file
    • re-create it with the stuff you want inserted at the start,
    • copy the renamed file in large chunks (not necessarily lines) to the end of the new file,
    • add the new bit at the end.

    This will be fast and memory-efficient.

    Of course, if your files are small enough to fit in memory, stick with what you have. It's good enough.

    Update:

    Enough people seem to be under the misapprehension that I'm advocating a shell script that I thought I'd set it straight. You can do all the things above from within native Perl.

    But you may want to consider if it's necessary to use Perl. A shell command like:

    ( echo '9   431';cat /usr/old;echo '(3,((((1,4),(7,6)),(2,8)),5),9)' ) >/usr/new
    

    will do the trick just as well (and probably just as fast).

    Of course, if you need Perl, then just ignore this update as the ramblings of an old man :-)

    0 讨论(0)
  • 2021-01-07 00:04

    There's many ways you can do it, for example with a simple shell script the way @Pax mentioned. You can also replace your array and loop with a join():

    open(DATA, "</usr/old") || die "cant open old\n"; #file to which line has to be added
    my $body=join("", <DATA>);
    open (FILE, ">/usr/new") || die "cant open new\n"; #file after stuff has been added
    print FILE "9   431\n";
    print(FILE $body);
    print FILE "(3,((((1,4),(7,6)),(2,8)),5),9)";
    close(FILE);
    
    0 讨论(0)
  • 2021-01-07 00:04

    you can do this

    open(FILE,">", $file) or die "cannot open $file: $!";
    print FILE "add line to top\n";
    while (<FILE>) { print $_ ."\n";}
    close(FILE);
    print FILE "add line to bottom\n";
    

    on command line

    perl myscript.pl > newfile
    
    0 讨论(0)
  • 2021-01-07 00:06

    Three answers have been given that perpetuate the very bad practice of:

    open(FILE,"<file") or die "cannot open";
    

    Not only that, the code is broken since you are not opening the file for writing but for reading.

    When an open fails, you can tell the user why it failed. Please get in the habit of including $! in the error message. Also, use the three argument form of open to separate the mode from the name:

    my $path="file";
    open my($fh), '>', $path or die "$path: $!";
    

    (This does not answer your question, but I'm making it an answer rather than a comment for added emphasis and so that I can review it as it is a rather lengthy spewing forth.)

    0 讨论(0)
  • 2021-01-07 00:09

    Use Tie::File which gives you access to the lines of a disk file via a Perl array. It comes with standard distribution.

    Example from documentation:

    use Tie::File;
    
    tie @array, 'Tie::File', filename or die ...;
    $array[13] = 'blah';     # line 13 of the file is now 'blah'
    print $array[42];        # display line 42 of the file
    
    $n_recs = @array;        # how many records are in the file?
    $#array -= 2;            # chop two records off the end
    
    for (@array) {
        s/PERL/Perl/g;         # Replace PERL with Perl everywhere in the file
    }
    
    # These are just like regular push, pop, unshift, shift, and splice
    # Except that they modify the file in the way you would expect
    push @array, new recs...;
    my $r1 = pop @array;
    unshift @array, new recs...;
    my $r2 = shift @array;
    @old_recs = splice @array, 3, 7, new recs...;
    
    untie @array;            # all finished
    
    0 讨论(0)
提交回复
热议问题