Perl文件操作实用技巧与示例
删除文件
利用unlink函数执行删除操作,例如unlink $file,或者同时删除多个文件如unlink $file1, $file2, $file3。
打开文件
推荐使用三参数形式的open函数来打开文件,这种方式能清晰地区分访问模式和文件名,且Perl 5.6及以上版本均支持该特性。复制代码 代码如下: #Open the 'txt' file for reading open FH, '<', "$file_name.txt" or die "Error:$!\n"; #Open the 'txt' file for writing. Creates the #file_name if it doesn't already exist #and will delete/overwrite a pre-existing file of the same name open FH, '>', "$file_name.txt" or die "Error:$!\n"; #Open the 'txt' file for appending. Creates the #file_name if it doesn't already exist open FH, '>>', "$file_name.txt" or die "Error:$!\n"; #Open the 'txt' file for a 'read/write'. #Will not create the file if it doesn't #already exist and will not delete/overwrite #a pre-existing file of the same name open FH, '+<', "$file_name.txt" or die "Error:$!\n"; #Open the 'txt' file for a 'read/write'. Will create #the file if it doesn't already exist and will #delete/overwrite a pre-existing file #of the same name open FH, '+>', "$file_name.txt" or die "Error:$!\n"; #Open the 'txt' file for a 'read/append'. Will create #the file if it doesn't already exist and will #not delete/overwrite a pre-existing file #of the same name open FH, '+>>', "$file_name.txt" or die "Error:$!\n";
一次性读入整个文件
在标量环境下使用<>可逐行读取,而在列表环境下则一次性读取所有行。$/变量存储行分隔符,默认为换行符。若希望一次性读入整个文件,可将$/设为undef,从而在标量环境中消除行的概念直接读取全部内容(也可用列表读取后拼接,但效率较低)。注意使用后需恢复$/的原值。复制代码 代码如下: #!/usr/bin/perl use strict ; use warnings ; sub test{ open FILE, '<', "d:/code/test.txt" or die $! ; my $olds = $/ ; $/ = undef ; my $slurp = ; print $slurp, "\n" ; $/ = $olds ; close FILE; } &test() ;
也可使用local关键字将$/设置为局部变量,这样退出当前作用域后,$/会自动恢复为原值。复制代码 代码如下: #!/usr/bin/perl use strict ; use warnings ; sub test{ local $/ ; #??? local $/ = undef ; open FILE, '<', "d:/code/zdd.txt" or die $! ; my $slurp = ; print $slurp, "\n" ; } &test() ; 1; 更推荐的做法是使用专用模块,如File::Slurp或IO::All,这样比手动编写更安全。
打开文件请用双引号
当open语句中的文件名包含变量替换时,建议使用双引号而非单引号,因为单引号不会进行变量内插。复制代码 代码如下: open FILE "<$file" or die $! ; #这样可以。 open FILE '<$file' or die $! ; #这样就不可以,因为$file不会被解释成变量内插。同样<也不会被解释成输入符号。
文件句柄作参数
如果有一个函数test接收文件句柄作为参数,可以通过以下两种方式传递:方法一是在传递参数时,在句柄前加*。
复制代码 代码如下: sub main { open FILE, '+<', 'test.data' or die $!; &test(*FILE); close FILE; }
方法二是使用open my $FILE的形式打开文件。复制代码 代码如下: sub main { open my $FILE, '+<', 'test.data' or die $!; &test($FILE); close $FILE; }