paso
paso

Reputation: 168

Reading in the First Line from a .txt File, Removnig it from the .txt., and Sliding all of the Other Lines Up by 1 Unit

I have a .txt file in which each line is only one element. As the subject suggests, I'd like to input the first row from the .txt. Then, I'd like to remove it from the .txt file as soon as I've inputted it. At the same time, I'd like to then slide each element up by one row such that the former second row element becomes the new first row.

I'm not quite sure how to proceed beyond: open( my $l, '<', 'Input.txt' ) or die "Can not open Input.txt: $!";

Upvotes: 1

Views: 246

Answers (4)

Kenosis
Kenosis

Reputation: 6204

Here's another option:

use strict;
use warnings;
use File::Slurp;

my $i = 0;
write_file $ARGV[0], grep $i++, read_file $ARGV[0];

Usage: perl script.pl inFile

The script uses File::Slurp in list context, and grep which allows the lines to pass only if $i isn't zero, so the first line is omitted, and lines 2 .. n are written back to the file.

Hope this helps!

Upvotes: 0

Ren&#233; Nyffenegger
Ren&#233; Nyffenegger

Reputation: 40543

When you use Tie::File, you can tie a file to an @array so that each element in the array corresponds to a line in the file.

In the following example, the shift operator removes the first element from @lines and assigns it to $first_line. Since @lines is tied to file.txt the first row in that file is also removed.

use strict;
use warnings;

use Tie::File;

tie my @lines, 'Tie::File', 'file.txt' or die $!;

my $first_line = shift @lines;

print "first line WAS: $first_line\n";

untie @lines;

Upvotes: 2

Jack
Jack

Reputation: 1912

use strict;

if ($#ARGV)
{
    print "\nUsage: test.pl Filename\n\n";
    exit();
}

my $f;
if (open($f, $ARGV[0]))
{
    print scalar(<$f>);

    my $s = join('', <$f>);
    close($f);

    if (open($f, '>', $ARGV[0]))
    {
        print $f $s;
        close($f);
    }
}
else print "\nCan't open input file $ARGV[0]\n\n";

or sub

sub slideFile($)
{
    my $filename = shift();

    my $f;
    if (open($f, $filename))
    {
        <$f>;

        my $s = join('', <$f>);
        close($f);

        if (open($f, '>', $filename))
        {
            print $f $s;
            close($f);
        }
    }
}

Upvotes: 2

ikegami
ikegami

Reputation: 386406

You can't remove from a file. You can simply read every byte that follows and write them back at the earlier position. This is expensive, but easy to do with Tie::File.

Upvotes: 2

Related Questions