Perl 6 > 视窗系统小工具、POE 和 Moo145


我们已经展示了如何用 Perl 6 创建一个小工具,展示了如何用 Perl 6 创建一个 POE 应用程序,展示了如何用 Perl 6 和 Moo 创建一个类。我们现在要将所有这些放在一起,创建一个视窗系统小工具,它将在后台使用 POE 和 Moo。

我们的一个小工具将显示系统的信息。具体来说,它将显示当前的 CPU 使用率和可用的内存。

首先,我们创建一个新的 Perl 6 模块:```perl 6
use v6;
module MyApp::SysInfoWidget {
use POE;
use Moo;
has $.cpu, .mem is rw;
}
```

这个模块使用 POE 和 Moo。`has` 方法创建了两个属性:`cpu` 和 `mem`。

接下来,我们创建一个类来表示一个小工具:```perl 6
class MyApp:: is Foo {
has $.cpu-label, $.mem-label is rw;
method new(Str $cpu-label, Str $mem-label) is new {
my $self = MyApp::;
$-label = $cpu-label;
$-label = $mem-label;
return $self;
}
}
```

这个类从 `Foo` 类继承。它有两个属性:`cpu-label` 和 `mem-label`。

接下来,我们创建一个 POE 组件来更新小工具的属性:```perl 6
component MyApp:: {
method POE::(POE::Session $session) is init {
my $sys-info = MyApp::;
my $cpu = POE::($session, 1, 1);
my $mem = POE::($session, 1, 1);
$ {
$ = (my $cpu = system("ps -eo %cpu | awk '{print $1}'")) // 'N/A';
};
my ($used, $total) = system("vm_stat | awk '{if (/Pages free:/) {$free = $3}} END {print $free,$total*4096}') // (0, -1);
my $mem-percent = $total == 0 ? 'N/A' : (100*(1 - $used/$total));
$ {
$ = $mem-percent . '%';
};
}
method POE::(POE::Session $session, Str $sig) is signal {
if ($sig eq 'cpu') {
POE::($session, 1.0, write($session, $sig));
}
if ($sig eq 'mem') {
POE::($session, 1.0, write($session, $sig));
}
}
method POE::(POE::Session $session, Str $sig) is write {
my $sys-info = MyApp::;
$($sig eq 'cpu' ? 'CPU' : 'Mem');
$($sig eq 'cpu' ? $ : $);
POE::(MyApp::, $sig, $sys-info);
}
}
```

这个组件使用 `POE::` 每秒更新一次小工具的属性。它还使用 `POE::` 广播更新。

最后,我们创建一个主程序来启动 POE 应用程序和小工具:```perl 6
sub MAIN(Str $argv) {
my $kernel = POE::;
my $session = $;
$(MyApp::);
my $widget = MyApp::('CPU', 'Mem');
$('CPU');
$('Mem');
$($session, $widget => sub ($widget, $msg, $data) {
say "cpu: $ mem: $";
});
$();
}
```

这个程序创建了一个 `POE::Kernel` 对象并启动了一个会话。然后它创建了一个 `MyApp::` 组件和一个 `MyApp::` 小工具。最后,它运行内核。

当您运行此程序时,它将在您的桌面上显示一个小工具,显示当前的 CPU 使用率和可用的内存。

2024-12-01


上一篇:perl多个if语句

下一篇:perl for 循环