Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I seem wisdodom dear monks! I need some ideas, on how to implement shortcuts in a menu-based front end. Basically, at any time, I would like an "F1" keypress to take the user to a specific menu option, and "F2" to another menu option. This would have to work at any time, even if in a nested subroutine, waiting on user input...

Replies are listed 'Best First'.
Re: Perl Hotkey/Shortcut
by zentara (Cardinal) on Aug 26, 2011 at 16:26 UTC
    This Glib event loop is console based. Below is the same basic script with a while loop instead of a Glib loop. Glib loops are nice because you can launch filewatchers and timers too.
    #!/usr/bin/perl use warnings; use strict; use Glib; use Glib qw/TRUE FALSE/; use Term::ReadKey; $|++; ReadMode('cbreak'); my $main_loop = Glib::MainLoop->new; Glib::Idle->add( sub{ my $char; if (defined ($char = ReadKey(0)) ) { print "$char->", ord($char),"\n"; #process key presses here } return TRUE; #keep this going }); $main_loop->run; ReadMode('normal'); # restore normal tty settings __END__
    with a plain while loop
    #!/usr/bin/perl use warnings; use strict; use Term::ReadKey; $|=1; ReadMode('cbreak'); my $key = ''; while ( $key ne 'q' ) { while (not defined ($key = ReadKey(-1))) { # No key yet } print "Get key '$key'\n"; print ord($key); print "\n"; } __END__ while(1){ my $char; if (defined ($char = ReadKey(0)) ) { print "$char->", ord($char),"\n"; # input was waiting and i +t was $char } else { # no input was waiting } } ReadMode('normal'); # restore normal tty settings

    I'm not really a human, but I play one on earth.
    Old Perl Programmer Haiku ................... flash japh
Re: Perl Hotkey/Shortcut
by Khen1950fx (Canon) on Aug 26, 2011 at 13:37 UTC
      To clarify, this menu is all text-based. None of it is windowed.
        To further clarify, user input is not a condition, just an example.
Re: Perl Hotkey/Shortcut
by RedElk (Hermit) on Aug 26, 2011 at 16:13 UTC

    Don't know if this will fit your needs but you might consider an until statement like the following:

    use strict; use warnings; $_ = ""; until (/^q/i) { print "What to do: ('o' for options)\n"; chomp ($_ = <STDIN>); if ($_ eq "o") { dboptions() } elsif {$_ eq "r" { readdb() } elsif ..... ..... else {print "Sorry, try again.\n";} } sub dboptions { print <<EOF; Your options are: o - view options r - read .... .... EOF }

    Gleaned from Chapter 13, Beginning Perl, page 441.