2012-08-02 60 views
2

我新的Perl和詛咒,但我努力讓我的代碼來運行一個循環,先從這裏是我的代碼:Perl的詛咒:: UI - 循環

#!/usr/bin/env perl 

use strict; 
use Curses::UI; 

sub myProg { 
    my $cui = new Curses::UI(-color_support => 1); 

    my $win = $cui->add(
     "win", "Window", 
     -border => 1, 
    ); 

    my $label = $win->add(
     'label', 'Label', 
     -width   => -1, 
     -paddingspaces => 1, 
     -text   => 'Time:', 
    ); 
    $cui->set_binding(sub { exit(0); } , "\cC"); 

    # I want this to loop every second 
    $label->text("Random: " . int(rand(10))); 
    sleep(1); 

    $cui->mainloop(); 

} 

myProg(); 

正如你所看到的我想這部分遞歸運行:

# I want this to loop every second 
    $label->text("Random: " . int(rand(10))); 
    sleep(1); 

投入標籤的隨機數的想法是隻是爲了顯示它的工作原理,我將最終有會定期更換相當多的標籤,想辦其他功能也是如此。

我試着這樣做:

while (1) { 
    ... 
} 

,但如果我這樣做,主循環之前();調用窗口永遠不會創建,調用之後它什麼也不做?

希望這有意義嗎?那我該怎麼做呢?

回答

5

一旦啓動主循環,Curses就會接管程序的執行流程,並且只通過您之前設置的回調將控制權返回給您。在這種模式下,您不需要使用sleep()循環執行時間相關的任務,而是要求系統定期回叫您更新。

重組程序來做到這一點,通過(無證)定時器:

#!/usr/bin/env perl 

use strict; 
use Curses::UI; 

local $main::label; 

sub displayTime { 
    my ($second, $minute, $hour, $dayOfMonth, $month, $yearOffset, $dayOfWeek, $dayOfYear, $daylightSavings) = localtime(); 
    $main::label->text("Time: $hour:$minute:$second"); 
} 

sub myProg { 
    my $cui = new Curses::UI(-color_support => 1); 

    my $win = $cui->add(
     "win", "Window", 
     -border => 1, 
    ); 

    $main::label = $win->add(
     'label', 'Label', 
     -width   => -1, 
     -paddingspaces => 1, 
     -text   => 'Time:', 
    ); 
    $cui->set_binding(sub { exit(0); } , "\cC"); 
    $cui->set_timer('update_time', \&displayTime); 


    $cui->mainloop(); 

} 

myProg(); 

如果你需要改變你的超時,set_timer也接受時間作爲額外的參數。相關功能enable_timer,disable_timerdelete_timer

來源:http://cpan.uwinnipeg.ca/htdocs/Curses-UI/Curses/UI.pm.html#set_timer-