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

Hi All, How do I read from a large log file remotely from the first 100 lines from the bottom up and then take that information and send it via email. I also want to remotly restart an NT service after that email goes out. Thanks again for you wisdom!
  • Comment on Reading Log file from bottom up and take first 100 lines and send email...

Replies are listed 'Best First'.
Re: Reading Log file from bottom up and take first 100 lines and send email...
by Courage (Parson) on Jul 19, 2002 at 06:24 UTC
    That's how you can restart service (you should have enough rights to do this):
    use strict; use Win32::OLE; my $service = "Print Spooler"; my $d = Win32::OLE->GetObject("WinNT://domainname"); # ... or just Get +Object("WinNT:") my $c = $d->GetObject("Computer", $opts{computer}); my $s = $c->GetObject("Service", "spooler"); eval {$s->Invoke('Stop');}; sleep 1; eval {$s->Invoke('Start');}; sleep 1;
    One of ways to get 100 lines from bottom will be:
    # unchecked code, sorry. my @x = <FH>; @x = @x[($#x-100>0?$#x-100:0)..$#x];

    Courage, the Cowardly Dog

      @x = @x[($#x-100>0?$#x-100:0)..$#x];
      I find   @x = @x[0..99] if @x > 100; to be more readable. YMMV.

        Well, the question was about taking the last 100 lines. You can use splice for that:
        splice @x => 0, -100;
        will keep the last 100 lines in @x. If you just want to keep the first 100, use
        splice @x => 100;
        Both will work without warnings if @x contains less than 100 elements.

        Abigail

        Good point. But it needs to be
        @x = reverse(@x[reverse -99..-1]) if @x > 100;
        ?

        updated sorry, I wrongfully read a question, I thought about *last* 100 lines. My wrong.

        Courage, the Cowardly Dog

      > my @x = <FH>; > @x = @x[($#x-100>0?$#x-100:0)..$#x];

      This will read in the whole log, quite inefficient if your log files are big..

      Consider this:

      open LOG,"<","/some/log" or die $!; seek LOG,-50000,2; # go to 50K from the end (assuming your log-lines +have 500 or less characters) my @lines = <LOG>; # get all from there splice @lines => 0, -100; # see [Abigail-II]'s comment close LOG; print @lines;
      </code>
      -- Joost downtime n. The period during which a system is error-free and immune from user input.