We often run OS command and other script from our perl scripts which need inputs. I am not talking about command line inputs but the inputs which is required at run time. For example we have a shell script as
echo "Enter Name :" read NAME; echo $NAME
Lets say this is myshell.sh. If we call this script from any perl script the script will stop and ask user to input name. But if we dont want to stop and want to input the name from perl script at run time, here is how can we do it:
Solution:
First of all
use IPC::Open3;
Now fork a new process which gives us handle of stdin,stdout,stderr streams.
my($WRITER, $READER, $ERROR); my $CMD="ss myshell.sh"; my $PID = open3($WRITER, $READER, $ERROR, $CMD);
The above code will fork a new process with Process ID as $PID. And we get three streams for writing to the process, reading from the process and error stream of process.
So when we want to pass inputs to ssh command we write to the WRITER.
print $WRITER "MY_NAME_IS_PERL\n";
And it works as we have interested ‘MY_NAME_IS_PERL‘ from command line.
Lets see a sample perl code
#!/usr/bin/perl use IPC::Open3; my $CMD = "sh myshell.sh"; print "\n Command =$CMD\n"; my($WRITER, $READER, $ERROR); my $PID = open3( $WRITER,$READER, $ERROR, $CMD); print "PID = $PID"; print $WRITER "MY_NAME_IS_PERL"; waitpid( $PID, 0 ); my $CHILD_EXIT_STATUS = $? >> 8; if ( $CHILD_EXIT_STATUS == 0 ) { print "\n Command Succeeded. Printing Output of command\n"; while (<$READER>) { print $_; } } else { print "\n Command Failed. Printing Output of command\n"; while (<$ERROR>) { print $_; } }
OUTPUT
Command Succeeded. Printing Output of command Enter Name : MY_NAME_IS_PERL