On Tue, 29 Oct 2002, zentara wrote:

> On Mon, 28 Oct 2002 13:54:28 -0500, [EMAIL PROTECTED] (Nikola
> Janceski) wrote:
>
> >without using 'tail' how can I get the trailing 5 lines of a large file
> >quickly, without loading it all to memory?
> >
> >is there anyway without pop and shifting through an array foreach line? (<=
> >this is the only way I could think of doing it)
>

If you are worried about memory usage, I guess you could try the following.

## untested code --

#! /usr/bin/perl5 -w
my (@arr, $flg, $no_of_lns);
$no_of_lns = 5;
$flg = 0;
open (F1, "< $file") or die("Cannot open $file: $!\n");
while (<F1>)
        {
        chomp;
        $arr[$#arr + 1 - $no_of_lns] = undef if ($flg == $no_of_lns);
        push @arr, $_;
        $flg++ if ($flg < $no_of_lns);
        }
close F1;

@arr = @arr[($#arr - $no_of_lns) .. $#arr];

I'm in a hurry so I haven't checked the code, but it should work

The idea is to push every line into an array, but undef the
fifth last element before adding the new line.

This way only five elements of the array actually contain lines,
while the rest are undefined elements.

Then at the end you can remove the last 5 elements of the array.

Although you have to go through the entire file atleast once,
your memory requirement won't increase.

bye,
George.


-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to