On 09/08/2017 11:41 PM, ToddAndMargo wrote:
Hi All!
I am trying to convert some Perl 5 code to Perl 6.
What do I use in place of
use Term::ReadKey qw ( ReadKey ReadMode );
I am trying to convert the following:
<code>
use Term::ReadKey qw ( ReadKey ReadMode );
sub DumpKeyboard () {
# Dump the contents of the keyboard buffer, if any
my $Trash;
ReadMode 4; # Turn off controls keys
while ( defined ( $Trash = ReadKey ( -1, \*STDIN ) ) ) {
# print "\$Trash = $Trash\n";
}
ReadMode 1; # Reset tty mode before exiting
}
</code>
Follow up as promised.
P6 comes with a built in "prompt" sub. It does it job.
But is not always appropriate as it
1) retains any trash deliberately or accidentally placed
in the keyboard buffer
2) it requires that you press enter to terminate the command
So, I build my own "Pause" command to deal with the problems
of "prompt":
1) dump (flush) the keyboard buffer
2) print out a message of your choosing
3) wait for a new (fresh) keyboard stroke
4) return the ASCII equivalent key that was pressed
So with a ton of help from you guys and the chat line, this
is what I have come up with.
Thank you all for the help!
-T
Pause.pm6
<code>
#!/usr/bin/env perl6
# Pause.pm6
#`{
References:
https://github.com/krunen/term-termios
https://github.com/ab5tract/Terminal-Print/blob/master/lib/Terminal/Print/RawInput.pm6#L17
https://linux.die.net/man/3/termios
# zef install Term::termios (as root)
# zef install Terminal::Print::RawInput (as root)
}
use Term::termios;
use Terminal::Print::RawInput;
sub Pause ( $PauseMessage) is export {
#`{
This sub will
1) dump (flush) the keyboard buffer
2) print out $PauseMessage
3) wait for a new (fresh) keyboard stroke
4) return the ASCII equivalent key that was pressed
Note: the GUI (Xfce, ec.) has precedence over reading
unusual keys, such as the "F" keys, etc.
}
my $char;
my $saved_termios;
my $termios;
# Save the previous attrs
$saved_termios := Term::termios.new(fd => 1).getattr;
# Get the existing attrs in order to modify them
$termios := Term::termios.new(fd => 1).getattr;
# Set the tty to raw mode
$termios.makeraw;
# int "\n";
print "$PauseMessage";
$saved_termios.setattr(:FLUSH);
my $in-supply = raw-input-supply;
react {
whenever $in-supply -> $c {
$char = $c.ord < 32 ?? '^' ~ ($c.ord + 64).chr !! $c;
# printf "got: %3d %2s %2s\r\n", $c.ord, $c.ord.base(16), $char;
# done if $c eq 'q';
done;
}
}
$saved_termios.setattr(:DRAIN) if $saved_termios;
print "$char\n";
return $char
}
</code>
And a tester for it:
Pause.pl6
<code>
#!/usr/bin/env perl6
use lib '/home/linuxutil';
use strict;
use Pause; # qw[ Pause ];
my @z = qw[z zz zzz zzzz snore];
say "Sleeping for ", @z.elems, " seconds. Press some keys.";
for @z { sleep 1; print "$_ " }; print "\n";
my $Key = Pause( 'Press any key to continue (including weird keys)... ' );
print "The key that was pressed was <$Key>\n";
</code>