2

私は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();

ご覧のとおり、このセクションを再帰的に実行する必要があります。

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

ラベルに乱数を入れるという考えは、それが機能することを示すためだけのものです。最終的には、定期的に変更されるかなりの数のラベルがあり、他の機能も実行したいと考えています。

私はやってみました:

while (1) {
    ...
}

しかし、mainloop();の前にこれを行うと、呼び出しウィンドウは作成されず、呼び出し後は何もしませんか?

これが理にかなっていることを願っていますか?では、どうすればよいですか?

4

1 に答える 1

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();

タイムアウトを変更する必要がある場合はset_timer、追加の引数として時間も受け入れます。関連機能enable_timerdisable_timerdelete_timer

ソース: http://cpan.uwinnipeg.ca/htdocs/Curses-UI/Curses/UI.pm.html#set_timer-

于 2012-08-02T13:08:11.000 に答える