Lesson 24: System calls


You will often have a need to execute commands that you would normally execute on the command line in you script. For example you might want to execute a series of scripts in one script.

There are two common ways to do this.

System

system is a function that you can supply the command line statement to be executed as the first argument and the exit status is returned. Output cannot be captured in a variable using system, but see backticks `` below for this feature.

  • 0 for no errors
  • -1 for errors
  • print "$!" for the reason)

Code:

1
2
my $sys = system ("date");
print "sys: $sys\n";

Output:

%% ./system.pl
Wed May  9 07:55:04 PDT 2012
sys: 0

Backticks ``

Backticks can be used to execute a command in your script. The output is the output of the command. This output can be captured in a variable. Now you can do things to the contents of the variable

Code:

1
2
3
4
my $output = `echo "using backticks is helpful"`;
##can do stuff to output
$output = uc ($output);
print "$output\n";

Output:

%% system.pl
USING BACKTICKS IS HELPFUL

Exercises

  1. Create a script that uses a system call, using the system function, to run one of your already written scripts. Collect the output of the system function in a variable and print it to the screen. This output is a code to indicate the success of the call.
  2. Change the script to run your system call using backticks. Collect your output and print it to the screen

Print Friendly

2 thoughts on “Lesson 24: System calls

  1. Sofia — I am using your 24-Step Program to teach my intern PERL. BTW, it’s annoying that you don’t have a link that says “Email Sofia” and I can’t find your address on the UC Riverside site;( Email me so I have your address!

Leave a Reply

Your email address will not be published. Required fields are marked *