【发布时间】:2017-08-24 23:37:10
【问题描述】:
如何从我的文件列表中删除第一行,这是我的代码,
打开我的目录:
use strict;
use warnings;
use utf8;
use Encode;
use Encode::Guess;
use Devel::Peek;
my $new_directory = '/home/lenovo/corpus';
my $directory = '/home/lenovo/corpus';
open( my $FhResultat, '>:encoding(UTF-8)', $FichierResulat );
my $dir = '/home/corpus';
opendir (DIR, $directory) or die $!;
my @tab;
while (my $file = readdir(DIR)) {
next if ($file eq "." or $file eq ".." );
#print "$file\n";
my $filename_read = decode('utf8', $file);
#print $FichierResulat "$file\n";
push @tab, "$filename_read";
}
closedir(DIR);
打开我的文件:
foreach my $val(@tab){
utf8::encode($val);
my $filename = $val;
open(my $in, '<:utf8', $filename) or die "Unable to open '$filename' for read: $!";
重命名文件
my $newfile = "$filename.new";
open(my $out, '>:utf8', $newfile) or die "Unable to open '$newfile' for write: $!";
删除第一行
my @ins = <$in>; # read the contents into an array
chomp @ins;
shift @ins; # remove the first element from the array
print $out @ins;
close($in);
close $out;
探测我的新文件是空的! rename $newfile,$filename or die "无法将 '$newfile' 重命名为 '$filename': $!"; }
这似乎是真的,但结果是一个空文件。
【问题讨论】:
-
应该有一种从 perl 内部调用命令的方法。有了这个,你需要做的就是
sed -e '1d' filename.txt -
因为我有很多文件如何更改 sed -e '1d' filename.txt 以同时从多个文件中删除第一行(文件目录)
-
在阅读之前,您应该在
$filename前面加上$directory:$filename = $directory . '/' . $filename。此外,在打开文件之前也没有必要对文件名进行编码。见this topic of SO docs -
另外,当将数组打印回文件时,您应该设置
$, = "\n"
标签: perl