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

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

    You could do something like:

    $data_file="somefile.txt";
    open(DAT, $data_file);
    @file_data = ;
    close(DAT);
    

    That'll give you the file contents in an array, that you can use for whatever you want, for example, if you wanted each individual line, you could do something like:

    foreach $LINE (@file_data)
    {
        dosomethingwithline($LINE);
    }
    

    For a full usage example:

    my $result;
    $data_file = "somefile.txt";
    my $opened = open(DAT, $data_file);
    if (!$opened)
    {
        $result = "Error.";
    }
    else
    {
        @lines = ;
        foreach $LINE (@lines)
        {
            $result .= $LINE;
        }
        close(DAT);
    }
    

    Then you can use $result however you need. Note: This code is untested, but it should give you an idea.

提交回复
热议问题