jreyesb has asked for the wisdom of the Perl Monks concerning the following question:

Hi everyone, Im newbie on perl and this site, i like it very much, most of all the top messages jejee like "Keep It Simple, Stupid" jajaja it kills me, ok, question. How can i delete the first 5 lines from a drive file, im doing this:
#!/usr/bin/perl use strict; use Tie::File; my @parsedfiles; my $n_files; if (-e "last_processed.log") { tie @parsedfiles, 'Tie::File', "last_processed.log"; n_files = @parsedfiles; if($n_files>=10) { for(my $i=0; $i<5; $i++) { delete $parsedfiles[$i]; } } untie @parsedfiles;
But!!! it just remove the content of the lines and my file looks like:
6chale 7chale 8chale 9chale 10chale 11chale 12chale
Help please!!!! Thanks in advanced

Replies are listed 'Best First'.
Re: Remove Lines from file
by Corion (Patriarch) on Jul 14, 2009 at 19:37 UTC

    You want shift, or splice, not delete, which is for hashes.

    Actually, delete also is documented to work on arrays, but it sets the array element to undef, which Tie::File turns into the empty string, which doesn't help you.

      Specifically,
      for(my $i=0; $i<5; $i++) { delete $parsedfiles[$i]; }
      should be
      splice(@parsedfiles, 0, 5);
Re: Remove Lines from file
by ikegami (Patriarch) on Jul 14, 2009 at 19:44 UTC
    perl -i.bak -ne'print if $. > 5' last_processed.log
Re: Remove Lines from file
by johngg (Canon) on Jul 14, 2009 at 22:06 UTC

    Another one-liner solution.

    $ perl -ne 'BEGIN { <> for 1 .. 5 } print' file > newfile

    Cheers,

    JohnGG

Re: Remove Lines from file
by Utilitarian (Vicar) on Jul 14, 2009 at 19:45 UTC
    As a crude one liner perl -e 'while (<>){if ($. > 5){print $_;}}' file >file.tmp;mv file.tmp file

    To add sophistication print to a file handle, ie

    use strict; use warnings; my ($FILE, $TEMP); open $FILE, "<", "file"; open $TEMP,">",file.tmp; while (<$FILE>){ if ($. > 5){ print $TEMP $_; } } close $FILE; close $TEMP; rename file.tmp, file;
Re: Remove Lines from file
by CountZero (Bishop) on Jul 14, 2009 at 19:45 UTC
    Replace your for-loop by
    shift @parsedfiles for (1..5);

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Re: Remove Lines from file
by ambrus (Abbot) on Jul 15, 2009 at 16:09 UTC
Re: Remove Lines from file
by johngg (Canon) on Jul 15, 2009 at 09:13 UTC

    It seems you can use a BEGIN {...} block with the -p flag to skip lines as well but it might be too succinct for its own good.

    $ perl -pe 'BEGIN { <> for 1 .. 5 }' file > newfile

    Cheers,

    JohnGG