Retrieving
Results from External Processes with Perl
In
theory, this is easy. All you need to do is something like...
$Result = `ls *.sql`
which
works perfectly well on any Unix (or Linux) system. The problem is that
it doesn't work at all on Windows so, if you want your programme to be
fully portable, you need a workaround. My solution is to use the one
common feature on both Windows and Unix, the redirection character
(>).
Say I want
to run a SQL query (because this is something I do
frequently, I have a subroutine for it)
#
=======================================
# Runs an SQL file, returning the result.
# ---------------------------------------
# $_[0] is the connection string.
# $_[1] is the file to run.
# $_[2] is a file to write the result to.
# ---------------------------------------
# (This last is necessary because the ``
# syntax does not work in Windows.)
# =======================================
sub
RunSqlQuery
{
my $V_COMMAND = "sqlplus "
. $C_SQLPLUS_FLAGS
. " "
. $_[0]
." \@"
. $_[1]
. " >"
. $_[2];
my $V_RESULT;
# --------------------------------
# Run the command created above...
# --------------------------------
TraceScript $Debug,
"RunSqlQuery",
"Running SQL Plus for [" . $_[1] . "]";
TraceScript $Paranoid,
"RunSqlQuery",
"Connect string is [" . $V_COMMAND . "]";
system $V_COMMAND;
#
---------------------------------
# Get the result back from the file
# and send it up
the call chain...
# ---------------------------------
$V_RESULT = ReadResultFile $_[2];
TraceScript $Debug, "RunSqlQuery", "SQL query run,
exiting.";
return $V_RESULT;
}
Now the
above piece of code will work, unaltered, on both Windows and
Unix. Then all we need to get at the result is...
#
===============================================
# Reads a file in which a result has been placed.
# -----------------------------------------------
# $_[0] name of the file to read.
# -----------------------------------------------
# This is one of the workarounds made necessary
# because the syntax "VAR=`command`" does not
# work in Windows the same as it does in Unix.
# ===============================================
sub ReadResultFile
{
my $V_BUFFER;
TraceScript $Debug,
"ReadResultFile",
"About to read
result file [" . $_[0] . "]";
open(H_SQL_FILE, "<$_[0]") or die "FAILURE:
Cannot open
" . $_[0];
read H_SQL_FILE, $V_BUFFER, 65535;
close H_SQL_FILE;
return $V_BUFFER;
}
The size
limit of 65535 bytes is arbitrary and you may wish to alter it
for your own requirements.
Find out more
by searching Google here...
|