Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

How to pipe console apps

0.00/5 (No votes)
13 Jul 2012 1  
Simulate user interaction in console apps with perl

Introduction 

This post describes how to interact with an interactive console application and similate user interaction.  In this case we are goint to interact with the app called mongo.exe wich is the console client for the NoSql database MongoDb.

Background 

Command line applications have been very useful because they allow us to perform actions easy and fast, the problem here is when you need to call a console application and such application require user interaction. Sometimes it becomes a headache for developers who want to call those apps to perform x or y actions, so here comes Perl to help us.

Using the code 

The following piece of code shows how to create a set of actions to execute when we call a console app.
#create a set of instructions
my @instructions = ();

push(@instructions, qq{use test;});
push(@instructions, qq{db.book.remove()});
push(@instructions, qq{db.book.save({name:"Code complete", author:"Steve Mcconnell"});});
push(@instructions, qq{db.book.save({name:"Perl: The Complete Reference", author:"Martin Brown"});});
push(@instructions, qq{db.book.find();});
push(@instructions, qq{exit});

#pipe the app in a handler
open MONGO, "| mongo.exe" || die "can't pipe mongo.exe";
#execute set of instructions
print MONGO join("\n",@instructions);
  

 To execute the previous code you just need to type perl filename.pl

Points of Interest 

Simulate user interaction in console apps may be tricky with other languages, in Perl is easy.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here