如何在Perl中读取文件并且如果文件不存在就创建它?

7
在Perl中,我知道这个方法:
open( my $in, "<", "inputs.txt" );

读取文件,但仅在文件存在时才执行。

使用“+”的另一种方式:

open( my $in, "+>", "inputs.txt" );

写入文件/如果文件存在则截断,这样我就没有机会读取文件并将其存储在程序中。

如何在Perl中读取文件,考虑文件是否存在?

好的,我已经编辑了我的代码,但文件仍然没有被读取。问题是它没有进入循环。我的代码有什么问题吗?

open( my $in, "+>>", "inputs.txt" ) or die "Can't open inputs.txt : $!\n";
while (<$in>) {
    print "Here!";
    my @subjects    = ();
    my %information = ();
    $information{"name"}     = $_;
    $information{"studNum"}  = <$in>;
    $information{"cNum"}     = <$in>;
    $information{"emailAdd"} = <$in>;
    $information{"gwa"}      = <$in>;
    $information{"subjNum"}  = <$in>;
    for ( $i = 0; $i < $information{"subjNum"}; $i++ ) {
        my %subject = ();
        $subject{"courseNum"} = <$in>;
        $subject{"courseUnt"} = <$in>;
        $subject{"courseGrd"} = <$in>;
        push @subjects, \%subject;
    }
    $information{"subj"} = \@subjects;
    push @students, \%information;
}
print "FILE LOADED.\n";
close $in or die "Can't close inputs.txt : $!\n";

你也可以先检查文件是否存在 if (-e "/filepath/file"){…} - vol7ron
不要自己编写文件数据存储的序列化器和解析器,我建议使用 YAMLJSON 来为您完成大部分工作。 - Miller
4个回答

12

使用适当的测试文件运算符

use strict;
use warnings;
use autodie;

my $filename = 'inputs.txt';
unless(-e $filename) {
    #Create the file if it doesn't exist
    open my $fc, ">", $filename;
    close $fc;
}

# Work with the file
open my $fh, "<", $filename;
while( my $line = <$fh> ) {
    #...
}
close $fh;

但如果文件是新的(没有内容),那么 while 循环就不会被执行。只有在测试正常的情况下才能更容易地读取文件:

if(-e $filename) {
   # Work with the file
   open my $fh, "<", $filename;
   while( my $line = <$fh> ) {
      #...
   }
   close $fh;
}

谢谢!通过使用-e,我学到了新的东西,现在它可以工作了。 - ejandra

4

您可以使用+>>进行读取/追加,如果文件不存在,则创建该文件但不截断它:

open(my $in,"+>>","inputs.txt");

0

首先检查文件是否存在。请参考下面的示例代码:

#!/usr/bin/perl
use strict;
use warnings;
my $InputFile = $ARGV[0];
if ( -e $InputFile ) {
    print "File Exists!";
    open FH, "<$InputFile";
    my @Content = <FH>;
    open OUT, ">outfile.txt";
    print OUT @Content;
    close(FH);
    close(OUT);
} else {
    print "File Do not exists!! Create a new file";
    open OUT, ">$InputFile";
    print OUT "Hello World";
    close(OUT);
}

0
接受答案中提出的解决方案可以用更少(更易读)的代码来编写,使用https://www.cpan.org上的File::Touch库。
use File::Touch;

my $file = 'a_file.txt';

touch($file) unless(-e $file);

如果你不介意在文件已经存在的情况下更新时间戳,甚至可以省略unless(-e $file)这一行。 - Boris Däppen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接