V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
darkbread
V2EX  ›  问与答

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

  •  
  •   darkbread · 2016-10-31 13:22:52 +08:00 · 2823 次点击
    这是一个创建于 2740 天前的主题,其中的信息可能已经有所发展或是发生改变。
    比如我有一个 data.txt ,内容里有若干换行,比如:
    para1

    para2

    para3


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

    my @contents = read_file($file_path);
    ```
    ltux
        4
    ltux  
       2016-10-31 17:28:15 +08:00   ❤️ 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
    ltux
        5
    ltux  
       2016-10-31 17:29:04 +08:00   ❤️ 1
    twl007
        6
    twl007  
       2016-11-01 04:12:57 +08:00   ❤️ 1
    while (<>) {
    push(@content, $_);
    }
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   832 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 19:38 · PVG 03:38 · LAX 12:38 · JFK 15:38
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.