如何在Perl中读取文件,如果它不存在则创建它?

eja*_*dra 6 perl file-io file

在Perl中,我知道这个方法:

open( my $in, "<", "inputs.txt" );
Run Code Online (Sandbox Code Playgroud)

读取文件,但只有文件存在才会这样做.

换句话说,带+的那个:

open( my $in, "+>", "inputs.txt" );
Run Code Online (Sandbox Code Playgroud)

写一个文件/截断如果它存在,所以我没有机会读取该文件并将其存储在程序中.

考虑文件是否存在,如何读取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";
Run Code Online (Sandbox Code Playgroud)

Mig*_*Prz 9

使用正确的测试文件操作符:

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;
Run Code Online (Sandbox Code Playgroud)

但是如果文件是新的(没有内容),则不会处理while循环.只有在测试结果正常时才能更容易地读取文件:

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