Skip to content
Prev 27054 / 398500 Next

Exception Handling

Zhongming Yang <Zhongming.Yang at cchmc.org> wrote:
Here's a little Perl script that invokes R.  If it is called with a positive
numerical argument, then R exits with that status, and Perl catches it via $?.
Note the script file in /tmp is saved (intentionally) if R exits abnormally.
See also the help pages for q(), stop(), and options("error").


#!/usr/local/bin/perl
(($arg1) = @ARGV) || die "Must pass a numerical argument.\n";
$script = "/tmp/rwrap$$.R";
open(SCRIPT, ">$script");
print SCRIPT <<EOF;
  arg1 <- $arg1
  options(error=expression(q(status=arg1)))
  if (arg1 > 0) log("a")
  q()
EOF
close(SCRIPT);
system("R --vanilla --slave < $script");
($Rstat = $?/256) && die "Aborted in R with status $Rstat.\n";
unlink $script;