PERL:写入输入文件(不覆盖原始文件)
下面是我的输入文件,也是我的输出文件。需要帮助读取和写入输入文件。(PS:输入和输出是同一个文件) 我的代码如下所示PERL:写入输入文件(不覆盖原始文件),perl,file,Perl,File,下面是我的输入文件,也是我的输出文件。需要帮助读取和写入输入文件。(PS:输入和输出是同一个文件) 我的代码如下所示 #!/usr/perl/5.14.1 use Getopt::Long; use strict; use warnings; my $file; GetOptions( "iofile=s" => \$file ); if (not defined $file){ print "Please specify input_output (iofile) fi
#!/usr/perl/5.14.1
use Getopt::Long;
use strict;
use warnings;
my $file;
GetOptions(
"iofile=s" => \$file
);
if (not defined $file){
print "Please specify input_output (iofile) file\n";
exit;
}
open (my $fh, "$file") or die "Can't open the file $file: ";
open (my $fh1, ">>$file") or die "Can't open the file $file: ";
while (<$fh>){
chomp $_;
next if ($_ !~ /S+/);
$_ =~ /(\S+)\s+(\S+)/;
my $first_underscore =index ($1, '_');
my $dev = substr ($1, $first_underscore + 1,
rindex ($1, '_') - $first_underscore - 1);
my $tag = $2;
my $cat_path = "/testdata/17.26.6/$dev/sd/$tag";
my $arc_path = "archive/$dev/sd/$tag";
if (-d $cat_path){
print $fh1 "$dev $tag IN_CAD\n";
}elsif (-d $arc_path){
print $fh1 "$dev $tag IN_ARCHIVE\n";
}else{
print $fh1 "NA\n";
}
}
print "Done! File been append.\n";
需要帮助,如果无论如何,我可以使输出如下
TS_dunit_ PDX_VER_6 IN_CAD
TS_test1_par PDX_VER_0 IN_CAD
在不覆盖文件其余部分的情况下,不能将其追加到文件中的某一行。文件是一个字节序列,我们不能“插入”新的字节,只能覆盖现有的字节(或通过扩展文件来添加更多字节)。例如,有关更多详细信息,请参见 相反,写出一个新文件,然后将其重命名为原始文件。这会改变inode编号;如果你需要保留它,请看结尾。该代码通过正则表达式简化了
索引
+子字符串
部分
use warnings;
use strict;
use feature 'say';
use File::Copy qw(mv);
# ... code from the question
open my $fh, '<', $file or die "Can't open $file:$!";
open my $fh_out, '>', $outfile or die "Can't open $outfile:$!";
while (<$fh>)
{
next if not /\S/;
chomp;
my ($dev, $tag) = /.*?_(.*)_\s+(.*)/;
my $cat_path = "/testdata/17.26.6/$dev/sd/$tag";
my $arc_path = "archive/$dev/sd/$tag";
if (-d $cat_path) {
say $fh_out "$_ IN_CAD";
}
elsif (-d $arc_path) {
say $fh_out "$_ IN_ARCHIVE";
}
else {
say $fh_out "NA";
}
}
close $fh;
close $fh_out;
# Changes inode number. See text for comment
move($fh_out, $fh) or die "Can't move $fh_out to $fh: $!";
使用警告;
严格使用;
使用特征“说”;
使用文件::复制qw(mv);
# ... 问题代码
打开我的$fh,'一个文件不能更改,以便添加到它的行中而不覆盖它。不要紧的是:根据需要编写输出文件(附加行),然后将其重命名为原始文件。最后,您可以根据需要更改原始文件。(在一个简单的方法中,inode编号会改变,你在乎吗?)非常感谢。非常重视你的建议,我现在正在编写代码…@Perlnewbie Great:)如果有问题,请告诉我
TS_dunit_ PDX_VER_6 IN_CAD
TS_test1_par PDX_VER_0 IN_CAD
use warnings;
use strict;
use feature 'say';
use File::Copy qw(mv);
# ... code from the question
open my $fh, '<', $file or die "Can't open $file:$!";
open my $fh_out, '>', $outfile or die "Can't open $outfile:$!";
while (<$fh>)
{
next if not /\S/;
chomp;
my ($dev, $tag) = /.*?_(.*)_\s+(.*)/;
my $cat_path = "/testdata/17.26.6/$dev/sd/$tag";
my $arc_path = "archive/$dev/sd/$tag";
if (-d $cat_path) {
say $fh_out "$_ IN_CAD";
}
elsif (-d $arc_path) {
say $fh_out "$_ IN_ARCHIVE";
}
else {
say $fh_out "NA";
}
}
close $fh;
close $fh_out;
# Changes inode number. See text for comment
move($fh_out, $fh) or die "Can't move $fh_out to $fh: $!";