Conditional whenever
I wrote a script to filter iostat because the latter either displays too much or too little. It also doesn’t know about bcache. I wanted to have the script react the same way to pressing q then top
, atop
or iotop
. But it should only watch the keyboard and quit when $*OUT
is a terminal. First we need to read the keyboard.
whenever key-pressed(:!echo) {
when 'q' | 'Q' { done }
}
Now we got a few options to add a check for an attached terminal
if $*OUT.t {
whenever key-pressed(:!echo) {
when 'q' | 'Q' { done }
}
}
$*OUT.t && do whenever key-pressed(:!echo) {
when 'q' | 'Q' { done }
}
do whenever key-pressed(:!echo) {
when 'q' | 'Q' { done }
} if $*OUT.t
The last one kind of lines up with other whenever
blocks but the condition gets harder to read. At first I thought it wont be possible to use ?? !!
because whenever
always wants to run .tap
on the parameter. But then I remembered that we use 0x90 to tell a CPU to do nothing. If we get a Supply
that does nothing we can opt out of doing something.
constant NOP = Supplier.new;
whenever $*OUT.t ?? key-pressed(:!echo) !! NOP {
when 'q' | 'Q' { done }
}
Now it neatly lines up with other whenever
blocks.
As a member of the Perl family Perl 6 has more then one way to do it. Most of them look a big odd though.
-
April 1, 2019 at 14:382019.13 No Jokes Today | Weekly changes in and around Perl 6