How do I read the contents of a small text file into a scalar in Perl?

后端 未结 8 778
日久生厌
日久生厌 2021-01-17 17:39

I have a small text file that I\'d like to read into a scalar variable exactly as it is in the file (preserving line separators and other whitespace).

The equivalent

相关标签:
8条回答
  • 2021-01-17 18:07

    Just join all lines together into a string:

    open(F, $file) or die $!;
    my $content = join("", <F>); 
    close F;
    

    (It was previously suggested to use join "\n" but that will add extra newlines. Each line already has a newline at its end when it's read.)

    0 讨论(0)
  • 2021-01-17 18:12

    There is a discussion of the various ways to read a file here.

    0 讨论(0)
提交回复
热议问题