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

后端 未结 8 781
日久生厌
日久生厌 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 17:55

    I'd tweak draegtun's answer like this, to make it do exactly what was being asked:

    my $buffer;
    if ( open my $fh, '<', 'fileName' ) {
        $buffer = do { local $/; <$fh> };
        close $fh;
    } else {
        $buffer = 'The file could not be opened.';
    }
    

提交回复
热议问题