在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";
答案 0 :(得分:7)
使用正确的test file operator:
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;
}
答案 1 :(得分:2)
您可以使用+>>
进行读取/追加,如果文件不存在但不截断文件,则创建该文件:
open(my $in,"+>>","inputs.txt");
答案 2 :(得分: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);
}