On Tue, 15 Mar 2005, Anish Kumar K. wrote:

> This program I use to get the last line from the log file "cipe.log". 
> and then write the line onto a text file "a.txt"
> 
> system("tail -1 cipe.log > a.txt");
> open INPUT,"a.txt";
> my $line=<INPUT>;
> 
> then I open the text file and read the value from the file handle.
 
You're very brave to not check that these commands work. 

Every one of them should have an "or die ..." (or "or croak ...") at the 
end to make sure that things are okay. More broadly, any time your 
program interacts with a system resource, you *must* check to be sure 
that the resource is actually available.

Therefore:

    my $commmand = "tail -1 cipe.log > a.txt";
    system($command)
        or die "Couldn't run command '$command': $!";
    my $cipetail = "a.txt";
    open CIPETAIL, <, $cipetail
        or die "Couldn't read from $cipetail: $!";
    my $slurp_in_whole_file = <CIPETAIL>
        or die "Couldn't read from $cipetail: $!";

And then when you close it, that needs to be handled as well:

    close CIPETAIL
        or die "Couldn't close $cipetail: $!";
 
> This invloves cumbersome process. I need to avoid writing to a file 
> the [output] of the system command. Is there a way to assign to some 
> variable...

That's an excellent thing to want to avoid.

For that matter, you shouldn't be using a system command in the first 
place -- Perl is perfectly capable of opening the file and reading in 
the last line. The _Perl Cookbook_ has a recipie that does almost what 
you want -- it truncates the last line, but we can amend that:

    open (FH, "+< $file")           or die "can't update $file: $!";
    while ( <FH> ) {
        $addr = tell(FH) unless eof(FH);
    }
    truncate(FH, $addr)             or die "can't truncate $file: $!";

    # ^ From <http://www.oreilly.com/catalog/cookbook/chapter/ch08.html>

So, if you omit the call to truncate, this does what you want. A version 
like this should be about right:

    my $cipelog = "cipe.log";
    open CIPELOG, <, $cipelog or die "Can't read from $cipelog: $!";
    while <CIPELOG> {
        my $line = tell CIPELOG unless eof CIPELOG;
    }
    close CIPELOG or doe "Couldn't close $cipelog: $!";

At this point, $line has the data you want.


 

-- 
Chris Devers

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to