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

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

    As an alternative to what Alex said, you can install the File::Slurp module (cpan -i File::Slurp from the command line) and use this:

    use File::Slurp;
    # Read data into a variable
    my $buffer = read_file("fileName");
    # or read data into an array
    my @buffer = read_file("fileName");
    

    Note that this dies (well... croaks, but that's just the proper way to call die from a module) on errors, so you may need to run this in an eval block to catch any errors.

提交回复
热议问题