Running operating system commands in Perl
Archive - Originally posted on "The Horse's Mouth" - 2008-07-08 18:37:03 - Graham EllisPerl is excellent "glueware" - a language which can be well used to connect together a whole lot of elements. And one of those elements may be operating system commands run from within the Perl program.
Here are (three!) ways that you can do it - in each case leaving the result of running the commands in a scalar variable.
# CAUTION - OS Dependent!
$imc = `uname -m`;
$imd = qx!uname -r!;
$imcalled = <<`DONE`
uname -s
date
uptime
DONE
;
# CAUTION - OS Dependent!
print ("***** Here document:\n$imcalled\n");
print ("***** Backquote:\n$imc\n");
print ("***** qx:\n$imd");
So that's
* A text string of commands in backquotes
* A text string of commands in a 'qx' string
* A text block (here document)
And here's how it runs:
BirthdayBoy:csr1 grahamellis$ perl bq
***** Here document:
Darwin
Tue 8 Jul 2008 18:41:38 BST
18:41 up 31 mins, 2 users, load averages: 0.01 0.05 0.06
***** Backquote:
Power Macintosh
***** qx:
9.0.0
BirthdayBoy:csr1 grahamellis$
You can also run operating system commands via a piped file handle, where you'll read back the response line by line:
open (FH,"ls -l *.*|");
while ($line = <FH>) {
print ++$n," ",$line;
}
Which gives us ...
BirthdayBoy:csr1 grahamellis$ perl lbl
1 -rw-r--r-- 1 grahamellis grahamellis 2856 7 Jul 16:35 dis.txt
2 -rw-r--r-- 1 grahamellis grahamellis 825 8 Jul 09:24 fred.txt
3 -rw-r--r-- 1 grahamellis grahamellis 3 7 Jul 10:04 pod2htmd.tmp
4 -rw-r--r-- 1 grahamellis grahamellis 3 7 Jul 10:04 pod2htmi.tmp
5 -rw-r--r-- 1 grahamellis grahamellis 502 8 Jul 14:28 tick.pm
BirthdayBoy:csr1 grahamellis$
(By the way - the name of my computer today - "BirthdayBoy" - has been allocated to me by the router at the hotel and does not imply anything about the day I was born!)