Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

Re: Run multiple shell commands on the same perl script

by Athanasius (Chancellor)
on Oct 31, 2012 at 02:20 UTC ( #1001590=note: print w/replies, xml ) Need Help??

in reply to Run multiple shell commands on the same perl script

Hello Daral, and welcome to the Monastery!

As 2teez explained, you can use system to run an external command from within a Perl script. But note that system returns the command’s exit status, not its output. If you want to capture the command’s output, use backticks (or the equivalent qx operator):

#! perl use strict; use warnings; my $ls = `ls`; print "Output from ls:\n\n", $ls, "\n"; my $con = `ipconfig`; print "Output from ipconfig:\n\n", $con, "\n";

Update: To capture both the output and the exit status, use the CPAN module Capture::Tiny.

Hope that helps,

Athanasius <°(((><contra mundum

Replies are listed 'Best First'.
Backticks and exit status
by space_monk (Chaplain) on Oct 31, 2012 at 14:25 UTC

    $? returns the result code from the last system() call or backtick operation, I believe, so you can both capture output and process result codes.


    #!/bin/perl # first command deliberately generates an error.... print `rubbish`; print "Rubbish Result: $?\n"; # this command should succeed print "ls Output:\n"; print `ls -l`; print "ls Result: $?\n";
    Rubbish Result: -1 ls Output: total 10 -rw-r--r-- 1 Userid Domain Users 1242 Oct 30 10:04 1.txt -rw-r--r-- 1 Userid Domain Users 1531 Oct 30 10:04 2.txt -rwxr-xr-x 1 Userid Domain Users 351 Oct 30 10:48 -rwxr-xr-x 1 Userid Domain Users 108 Oct 31 14:21 ls Result: 0
    Note the first output of $? is -1 (an error), whilst the second is 0 (success)

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1001590]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (7)
As of 2017-04-25 18:05 GMT
Find Nodes?
    Voting Booth?
    I'm a fool:

    Results (462 votes). Check out past polls.