Perl Curses :: UI - 循环

Dav*_*owe 2 curses perl loops

我是Perl和Curses的新手,但是我很难让我的代码运行循环,从这里开始我的代码:

#!/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();
Run Code Online (Sandbox Code Playgroud)

如您所见,我希望此部分以递归方式运行:

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

在标签中放置一个随机数的想法只是为了表明它是有效的,我最终会有很多标签会定期更改,并且还想做其他功能.

我试过做:

while (1) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

但如果我在mainloop()之前这样做; 从不创建调用窗口,调用后它什么都不做?

希望这有道理吗?那我该怎么做?

the*_*mel 6

启动主循环后,Curses将接管程序的执行流程,并且只通过之前设置的回调将控制权返回给您.在这个范例中,您不会使用sleep()循环执行与时间相关的任务,而是要求系统定期回拨您的更新.

通过(未记录的)Curses::UI计时器重构您的程序以实现这一目的:

#!/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();
Run Code Online (Sandbox Code Playgroud)

如果您需要更改超时,set_timer也可以将时间作为附加参数.相关功能enable_timer,disable_timer,delete_timer.

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