darkbread
V2EX  ›  问与答

问下 perl 怎么读取整个文件里的内容(包括所有换行)?

  •  
  •   darkbread · Oct 31, 2016 · 3617 views
    This topic created in 3496 days ago, the information mentioned may be changed or developed.
    比如我有一个 data.txt ,内容里有若干换行,比如:
    para1

    para2

    para3


    我想把整个文本保存到变量里,可是我用 open 时,一遇到换行就返回了,只能得到 para1 。
    6 replies    2016-11-01 04:12:57 +08:00
    xss
        2
    xss  
       Oct 31, 2016   ❤️ 1
    open F,'<','./lsmod.log' or die('open failed');
    @content = <F>;
    cfy
        3
    cfy  
       Oct 31, 2016   ❤️ 1
    ``` Perl
    use File::Slurp qw/read_file/;

    my @contents = read_file($file_path);
    ```
    ltux
        4
    ltux  
       Oct 31, 2016   ❤️ 1
    Perl 官方文档
    Perl FAQ: How can I read in an entire file all at once?
    http://perldoc.perl.org/perlfaq5.html#How-do-I-print-to-more-than-one-file-at-once%3f
    twl007
        6
    twl007  
       Nov 1, 2016   ❤️ 1
    while (<>) {
    push(@content, $_);
    }
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   928 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 20:50 · PVG 04:50 · LAX 13:50 · JFK 16:50
    ♥ Do have faith in what you're doing.