I have a program that takes input from the keyboard and presents a nice visualization. The purpose of the program is so that my infant can mash on the keyboard and get the computer to do something.

However, I would like to write a keyboard input sanitizer that is disjoint from the main program. Conceptually, I would want the program have the functionality:

  sanitize_keyboard_input | my_program

Where my_program thinks it is getting input from the keyboard but it is really getting input from sanitize_keyboard_input. Is there a way to do this? I am running Ubuntu linux if that helps.

1 Answer 1


I wrote this a long time ago. It's a script that sits between the user's input and an interactive program, and allows the input to be intercepted. I used it to escape to the shell to check filenames when running old Fortran programs that asked lots of questions. You could easily modify it to intercept particular inputs and sanitize them.


# shwrap.pl - Wrap any process for convenient escape to the shell.

use strict;
use warnings;

# Provide the executable to wrap as an argument
my $executable = shift;

my @escape_chars = ('#');             # Escape to shell with these chars
my $exit = 'bye';                     # Exit string for quick termination

open my $exe_fh, "|$executable @ARGV" or die "Cannot pipe to program $executable: $!";

# Set magic buffer autoflush on...
select((select($exe_fh), $| = 1)[0]);

# Accept input until the child process terminates or is terminated...
while ( 1 ) {
   chomp(my $input = <STDIN>);

   # End if we receive the special exit string...
   if ( $input =~ m/$exit/ ) {
      close $exe_fh;
      print "$0: Terminated child process...\n";

   foreach my $char ( @escape_chars ) {
      # Escape to the shell if the input starts with an escape character...
      if ( my ($command) = $input =~ m/^$char(.*)/ ) {
         system $command;
      # Otherwise pass the input on to the executable...
      else {
         print $exe_fh "$input\n";

A simple example test program you can try it out on:


while (<>) {
   print "Got: $_";
  • Thank you. This is very useful. I think that I will have to make some modifications to not use chomp, which does line-by-line, right? My program responds to individual key events, not separated by newline. But, I like the general idea and I can make this work. Thank you!
    – stevejb
    Nov 4, 2012 at 23:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.