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

Wise Monks, How do I poll for input - as in:

AND keep a Tk window happy? I seem to get memory faults and run-time errors..

Replies are listed 'Best First'.
Re: Tk and blocking loops
by graff (Chancellor) on Mar 09, 2003 at 03:33 UTC
    Look up "Tk::fileevent":
    Tk::fileevent - Execute a callback when a filehandle becomes readable or writable SYNOPSIS $widget->fileevent(fileHandle,readable?,callback?) $widget->fileevent(fileHandle,writable?,callback?) DESCRIPTION This command is used to create file event handlers. A file event handler is a binding between a filehandle and a callback, such that the callback is evaluated whenever the filehandle becomes readable or writable. File event han­ dlers are most commonly used to allow data to be received from another process on an event-driven basis, so that the receiver can continue to interact with the user while waiting for the data to arrive...
      graff is right. Basically, Tk would get all the events, and those events are no longer delivered to your code directly.

      Another example is that you would not be able to call sleep in your Tk scripts, if you want to do something periodically, you would have to call after.
Re: Tk and blocking loops
by Dr. Mu (Hermit) on Mar 09, 2003 at 09:05 UTC
    If you are able to poll your input channel to see whether there's any data waiting before attempting to read it (as you can with serial input), you might consider doing so in a repeat callback. I've done this using a string as a queue, appending new data to the end, and processing (and deleting) syntactic chunks as they appear. (Regexes are great for recognizing and extracting such chunks.)

    When such polling is not possible, you can use fileevent, but I might think twice about trying to handle the data every time it triggers a callback. Better just to enqueue it and get out. Then use a repeat callback to recognize, dequeue, and process the data at a controllable rate. That way you won't be trying to process every individual byte as it comes in at the risk of slowing GUI response to a crawl.

Re: Tk and blocking loops
by schweini (Friar) on Mar 10, 2003 at 03:53 UTC
    it's not really worth a seperate SoPW, so i just wanted to ask here if i'm correct in assuming that this whole fileevent doesn't really work on win32, or am i mistaken? (if someone says that it DOES work, i'll at least know that i have to try harder)..

      fileevent doesn't work with ActivePerl 5.6.1 or 5.8.0. I'm not sure about other versions. I'm really upset about the whole thing, too, since POE requires fileevent to work with Tk.

      Anyway, here's a test case (pure Tk) that you can use to verify whether fileevent works with your OS/Perl/Tk environment. It should be portable across UNIX and Win32.

      -- Rocco Caputo - troc@pobox.com - poe.perl.org