Thursday, 22 October 2009

Perl wrapper for R

This Perl wrapper for R fills in some missing functionality (line number and context on error) and automatically 'dumps' the output of the script.

I can be improved in many ways, but here it is, as is....


   1. #! /usr/bin/perl -w
   2.
   3. unless (@ARGV){
   4.   warn "\n";
   5.   warn "Runs an R script with STDERR dumped to STDOUT\n\n";
   6.   warn "Usage: $0 \n\n";
   7.   exit(1);
   8. }
   9.  
  10. my $rFile = shift @ARGV;
  11.  
  12. die "Stubbornly refusing to run R on a file that doesn't end .R!\n"
  13.   unless $rFile =~ /\.R$/;
  14.  
  15. my $oFile = `basename $rFile .R`; chomp( $oFile );
  16.  
  17. my $args = join(" ", @ARGV);
  18.  
  19. if ($args){
  20.   $args = "--args $args";
  21. }
  22.  
  23. warn "Using: R $args < $rFile > $oFile.dump\n";
  24.  
  25.  
  26.  
  27. open ( OH, ">$oFile.dump" )
  28.   or die "cant : $! \n";
  29.  
  30. my $pid =
  31.   open( PH, "R $rFile -q --vanilla $args < $rFile 2>&1 |" )
  32.     or die "cant : $? : $! \n";
  33.  
  34. my $lineNumber;
  35.  
  36. while(){
  37.   $lineNumber++ if /^(\>|\+)/o;
  38.   print OH;
  39. }
  40.  
  41. close( OH );
  42. close( PH );
  43.  
  44. if ($?) {
  45.   #warn "killed by $?\n";
  46.   warn "FAILED AT LINE $lineNumber\n";
  47.   system("tail -n 5 $oFile.dump");
  48.   exit(1);
  49. }
  50.  
  51. warn "OK (NO ERRORS DETECTED)\n";

Post a Comment