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

Hi esteem monks,

I wanna read content of file to text widget. It appends a new line every 3 sec. Below is my code:
use strict; use warnings; use Tk; my $mw = MainWindow->new(); my $st = $mw->Scrolled("Text",-scrollbars => "eo")->pack(); $st->repeat(3000,\&list); MainLoop; sub list { my $fh; open ($fh, "<D:\\perl_script\\sqlnet.log") or die "error!!$!\n"; while (<$fh>) { $st->insert("end", $_); } close ($fh); }
But it doesn't work well. Every 3 sec, text widget showed a page, not a line, furthermore, the slider doesn't jump to the end of the text, so you have to drag it to see new added contents.

any suggestions?


I am trying to improve my English skills, if you see a mistake please feel free to reply or /msg me a correction

Replies are listed 'Best First'.
Re: insert in Text widget
by shmem (Chancellor) on May 25, 2007 at 08:10 UTC
    You are reading the entire file in that loop:
    while (<$fh>) { $st->insert("end", $_); }

    You probably want

    use strict; use warnings; use Tk; my $fh; open ($fh, "<D:\\perl_script\\sqlnet.log") or die "error!!$!\n"; my $mw = MainWindow->new(); my $st = $mw->Scrolled("Text",-scrollbars => "eo")->pack(); my $id = $st->repeat(3000,\&list); MainLoop; close ($fh); sub list { if (eof($fh)) { $st->aftercancel($id); return; } my $line = <$fh>; $st->insert('end', $line); $st->see('end'); }

    Roughly.

    --shmem

    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
      Thank you!!! It works!

      I am trying to improve my English skills, if you see a mistake please feel free to reply or /msg me a correction
Re: insert in Text widget
by Khen1950fx (Canon) on May 25, 2007 at 21:53 UTC
    shmem's code is great++. I took a different tack, cleaned your code up a little, and came up with this:

    #!/usr/bin/perl use strict; use warnings; use Tk; use IO::File; my $mw = MainWindow->new(); my $st = $mw->Scrolled( 'Text', -scrollbars => 'eo' )->pack(); $st->repeat( 3000, \&list ); MainLoop; sub list { my $fh = IO::File->new(); open $fh, q{<}, '/usr/lib/perl5/site_perl/5.8.8/i386-linux-thread- +multi/Tk/Text.pm'; while (<$fh>) { $st->insert( 'end', "line $_\n" ); return; } } 1;

    Update: Fixed. It should work now. Sorry for the delay. The main reason that I did it this way is that I used Perl::Critic, and it recommended IO::File. Also, it recommended a 3-arg open, which seems to work a little better. There's an online Perl::Critic at http://perlcritic.com/

      I've try your code, but it seems not work. Could you comment your key changes?


      I am trying to improve my English skills, if you see a mistake please feel free to reply or /msg me a correction