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

后端 未结 9 1188
自闭症患者
自闭症患者 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-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 :-)

提交回复
热议问题