Making SAS Interactive (Part 1): Using stdin and stdout

This post was kindly contributed by SASopedia - go there to comment and to read the full post.

Many a times, we may come across a need for having a dynamic programs. Meaning, we may need the user to key in the input and run the code accordingly, based on his input. This can be achieved in SAS by using the automatic file descriptors: stdin and stdout. This is more widely used in UNIX environment, especially when we batch submit the code in the command line.

In the below code, I illustrate the use of stdin and stdout by implementing a simple calculator, which takes in the numbers and the operators as the arguments and outputs the results.

data test;
if (_N_ eq 1) then do;
 file stdout;
 infile stdin;
 put @1 “Enter the first variable:”;
 input X @;
 put @1 “Enter the second variable:”;
 input Y @;
 put @1 “Choose the operator: + – * / **:”;
 input op $;
end;
retain X Y op;
select (op);
 when (‘+’) result=X+Y;
 when (‘-‘) result=X-Y;
 when (‘*’) result=X*Y;
 when (‘/’) result=X/Y;
 when (‘**’) result=X**Y;
 otherwise ;
end;
put “The result is:” result;
run;

In the above code, I’ve redirected the infile and file statements to the stdin and stdout respectively. So the input is always read through the terminal key and the output is always written to the terminal.

When we run the above code in the batch mode, we get the following output:

We can also route the output of a procedure into the terminal using the proc printo as shown below:

proc printto print=stdout;
run;

The below code would output all the details of the student whose name is keyed in the terminal for the sashelp.class dataset:

data name;
title;
if (_N_ eq 1) then do;
 file stdout;
 infile stdin;
 put @1 “Enter the student name:”;
 input n $;
end;
retain n;
call symput(‘name’,n);
run;

proc printto print=stdout;
run;
options nodate nonumber;
proc print data=sashelp.class noobs;
where name=”&name”;
run;

This would give us the below output:

Let me know if you guys have any thoughts or other approaches.

More to come: Making SAS Iinteractive (Part 2): Using window prompts

This post was kindly contributed by SASopedia - go there to comment and to read the full post.