Here's a way without the external module. It's very basic, but could give you some guidance to make it more complex. Uses a dispatch table to run commands based on what the user enters, and will run the last command typed if user hits the up arrow.
Essentially, all you have to do is keep history in an array outside of your main game loop, then push to it every round. When the up arrow is seen, you need to pull the last entry from the history array, and use it.
#!/usr/bin/perl use strict; use warnings; my $up_arrow = "\e[A"; # up arrow my @history = []; my %dispatch = ( 'fight' => \&fight, 'run' => \&run, ); while(1){ print "Enter command...\n"; my $in = <STDIN>; chomp $in; if ($in eq $up_arrow){ print "$history[-1]"; push @history, $history[-1]; $dispatch{$history[-1]}->(); } else { push @history, $in; $dispatch{$in}->(); } } sub fight(){ print "Everybody was kung-fu fighting!\n"; } sub run(){ print "I'm running the hell away!\n"; }
Input/output:
steve02@steve02-ws:~$ ./arrow.pl Enter command... run I'm running the hell away! Enter command... ^[[A runI'm running the hell away! Enter command... fight Everybody was kung-fu fighting! Enter command... ^[[A fightEverybody was kung-fu fighting! Enter command...
EDIT: I often like to make code examples a little more complex than necessary to give requesters things to think about, but in this case, I may have gone a bit over the top. This is likely because now coding in Python, I like to exercise my Perl when I can :)
Here's a more basic example of how one could do what OP asked. Note that if *only* the most recent history is ever needed, it would be advisable to shift off of the history array each iteration as to not eat up all memory if the plan is to do many, many iterations.
The following code asks the user for a number, and prints the result of that number multiplied by 10. Hitting the up arrow will perform the same calculation with the same number as last round.
#!/usr/bin/perl use warnings; # always use this use strict; # always use this my $up_arrow = "\e[A"; # up arrow control character my @history = []; my $number = 10; while(1){ print "Enter a number...\n"; my $input = <STDIN>; chomp $input; if ($input eq $up_arrow){ $input = $history[-1]; } push @history, $input; my $result = $number * $input; print "\nResult of $input x $number is: $result\n"; }
Cheers,
-stevieb
In reply to Re: How to add input history
by stevieb
in thread How to add input history
by zsl
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |