PeterHsu
PeterHsu

Reputation: 121

How to do 'Wait and Answer to System' with Perl

I am writing a Perl that automatically interacts with another script.
The script needs double confirm for some critical operations.

Executing the script without Perl is something like the following:

$ ./TheScript
TheScript Starting.......
Following step might be harmful to your system.
Are You Sure (Y/N)?
$ Y
TheScript finished!

Now I want a Perl script doing that for me. I am sure that (Y/N) confirmation will exist within 10 sec. So I've tried:

system('./TheScript');
sleep 10;
system('Y');

This failed because it stuck in system('./TheScript') and did not
go to the rest of the script including reply 'Y'.

Backstick ` is almost the same as system except it captures the STDOUT.
exec() is more impossible because it forks TheScript and is not able to do anything on it again.

Did I make any mistakes doing the analysis? Or are there any functions doing what I want?

Upvotes: 1

Views: 217

Answers (2)

Nilesh
Nilesh

Reputation: 1

As per your written Perl script, you are facing issue when double confirmation occurred by the system. So for that I can suggest, you can write the script in such way that ,

first it checks first confirmation OK fine if next again it asks confirmation , your script must check second confirmation as well

for this ,

my $conf= "Are You Sure (Y/N)?"; my $length = $conf; if ($length > 0) { sleep 0; system('Y'); } else { system('N'); }

I hope , this script will be fine for you.

Upvotes: 0

cjm
cjm

Reputation: 62109

You misunderstand the system function. It waits for the program to exit before your Perl program continues.

To drive an interactive program from Perl, you want the Expect module (or perhaps Expect::Simple). However, for a very simple case like you're suggesting, IPC::Open2 may suffice, and it's a core module.

Upvotes: 2

Related Questions