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

后端 未结 8 779
日久生厌
日久生厌 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:02

    From the Perl Cookbook:

    my $filename = 'file.txt';
    open( FILE, '<', $filename ) or die 'Could not open file:  ' . $!;
    
    undef $/;
    my $whole_file = ;
    

    I would localize the changes though:

    my $whole_file = '';
    {
        local $/;
        $whole_file = ;
    }
    

提交回复
热议问题