Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...