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

I'm using Tie::File to delete the first line in my file, but it's leaving the "\n". Is there a way to get Tie::File to also delete the "\n" newline?

Here's my code:
use Tie::File; my $file = "file.csv"; tie my @lines, Tie::File, $file or die "can't update $file: $!"; delete $lines[1];

Replies are listed 'Best First'.
Re: Tie::File Deleting Lines Including "\n"
by ikegami (Patriarch) on Oct 04, 2005 at 20:38 UTC

    delete on a Tie::File array leaves the newline in order to behave as closly as possible to a real array. You want to use splice:

    use Tie::File; my $file = "file.csv"; tie my @lines, Tie::File, $file or die "can't update $file: $!"; splice(@lines, 1, 1);

    Update: I assumed you meant "first line pass the header" or something like that. If you truly want to delete the first line, you can use:

    splice(@lines, 0, 1);

    or

    shift(@lines);
      Ahh, I get it. I didn't understand that the file is now like an array and you can use array functions on it.

      Thanks!
Re: Tie::File Deleting Lines Including "\n"
by sk (Curate) on Oct 04, 2005 at 20:42 UTC
    from  perldoc -f delete

    Deleting an array element effectively returns that position of the arr +ay to its initial, uninitialized state. Subsequently testing for the + same element with exists() will return false. Note that deleting ar +ray elements in the middle of an array will not shift the index of th +e ones after them down--use splice() for that. See "exists".

    The array has not shrunk in size.

    #!/usr/bin/perl -w my @array = (1, 2, 3, 4); print "length = ", scalar @array,$/; delete $array[2]; print "length = ", scalar @array,$/; __END__ length = 4 length = 4

    If it is just the second element (index = 1) then you can also do this simple assignment and shift. If you want to move around quite freely use splice.

    infile

    first second third fourth

    use Tie::File; my $file = "file.csv"; tie my @lines, Tie::File, $file or die "can't update $file: $!"; $lines[1] = $lines[0]; shift(@lines); untie @lines;
    outfile
    first third fourth
Re: Tie::File Deleting Lines Including "\n"
by sauoq (Abbot) on Oct 04, 2005 at 20:51 UTC
    I'm using Tie::File to delete the first line in my file ... delete $lines[1];

    Other's have pointed out the problem with delete. I thought someone should point out that that's not the first line in your file. It's the second line. Arrays in perl are (usually) zero-based.

    -sauoq
    "My two cents aren't worth a dime.";
    
Re: Tie::File Deleting Lines Including "\n"
by pg (Canon) on Oct 04, 2005 at 20:46 UTC
    splice(@lines, 1, 1);

    If you try this, both print statements give you 2.

    use strict; use warnings; my @a = (1,2,3); print $#a, "\n"; delete $a[1]; print $#a, "\n";