2012-08-02 74 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-