Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
265 views
in Technique[技术] by (71.8m points)

perl - Remove the first line from my directory

how can i remove the first line from my list of file , this is my code,

open my directory:

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
";

my $filename_read = decode('utf8', $file); 
        #print $FichierResulat "$file
";

push @tab, "$filename_read";

}
 closedir(DIR);

open my file:

foreach my $val(@tab){


utf8::encode($val);

my $filename = $val;

open(my $in, '<:utf8', $filename) or die "Unable to open '$filename' for read: $!";

rename file

my $newfile = "$filename.new";

open(my $out, '>:utf8', $newfile) or die "Unable to open '$newfile' for write: $!";

remove the first line

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;

the probem my new file is empty ! rename $newfile,$filename or die "unable to rename '$newfile' to '$filename': $!"; }

It seems true but the result is an empty file.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The accepted pattern for doing this kind of thing is as follows:

use strict;
use warnings;

my $old_file = '/path/to/old/file.txt';
my $new_file = '/path/to/new/file.txt';

open(my $old, '<', $old_file) or die $!;
open(my $new, '>', $new_file) or die $!;

while (<$old>) {
    next if $. == 1;
    print $new $_;
}

close($old) or die $!;
close($new) or die $!;

rename($old_file, "$old_file.bak") or die $!;
rename($new_file, $old_file) or die $!;

In your case, we're using $. (the input line number variable) to skip over the first line.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...