Home » Faqs » System » System |
You want to call another program from your perl program.
You can call any program like you would from the command line using a system call. This is only useful if you do not need to capture the output of the program.
#!/usr/bin/perl use strict; use warnings; my $status = system("vi fred.txt");
Or if you don't want to involve the shell:
#!/usr/bin/perl use strict; use warnings; my $status = system("vi", "fred.txt");
You'll need to bitshift the return value by 8 (or divide by 256) to get the return value of the program called:
#!/usr/bin/perl use strict; use warnings; my $status = system("vi", "fred.txt"); if (($status >>=8) != 0) { die "Failed to run vi"; }
If you need to capture the output of the program, use qx.
#!/usr/bin/perl use strict; use warnings; my $info = qx(uptime); print "Uptime is: $info\n";
Or if the output has multiple lines (e.g. the output of the "who" command can consist of many lines of data):
#!/usr/bin/perl use strict; use warnings; my @info = qx(who); foreach my $i (@info) { print "$i is online\n"; }
You can also use backticks (`) to achieve the same thing:
#!/usr/bin/perl use strict; use warnings; my @info = `who`; foreach my $i (@info) { print "$i is online\n"; }
Run
perldoc perlop
and refer to the qx section.