使用 Perl 读写文件

写入文件

#!/usr/bin/perl
use strict;
use warnings;

use Path::Tiny;
use autodie; # die if problem reading or writing a file

my $dir = path("/tmp"); # /tmp

my $file = $dir->child("file.txt"); # /tmp/file.txt

# Get a file_handle (IO::File object) you can write to
# with a UTF-8 encoding layer
my $file_handle = $file->openw_utf8();

my @list = ('a', 'list', 'of', 'lines');

foreach my $line ( @list ) {
    # Add the line to the file
    $file_handle->print($line . "\n");
}

追加到文件

# As above but use opena_utf8() instead of openw_utf8()
my $file_handle = $file->opena_utf8();

读取文件

#!/usr/bin/perl
use strict;
use warnings;

use Path::Tiny;
use autodie; # die if problem reading or writing a file

my $dir = path("/tmp"); # /tmp

my $file = $dir->child("file.txt");

# Read in the entire contents of a file
my $content = $file->slurp_utf8();

# openr_utf8() returns an IO::File object to read from
# with a UTF-8 decoding layer
my $file_handle = $file->openr_utf8();

# Read in line at a time
while( my $line = $file_handle->getline() ) {
        print $line;
}

Path::Tiny 使得使用目录和文件变得简洁且容易。使用 path() 为任何要操作的文件路径创建一个 Path::Tiny 对象,但请记住,如果你要调用其他 Perl 模块,可能需要使用“stringify”将对象转换为字符串

    $file->stringify();
    $dir->stringify();
    

autodie 强制许多函数在失败时使用有用的错误消息终止(而不是返回 undef)。这使得代码更简洁。要检查和捕获错误,请使用 Try::Tiny