[Techtalk] using shell commands in perl scripts

Rasjid Wilcox rasjidw at openminddev.net
Sun May 25 17:06:40 EST 2003


On Sunday 25 May 2003 12:47, Berenice wrote:
> I've just started perl as part of my course and I'm wondering how you
> can use commands such as rm, mkdir and less in perl scripts.

Below is a short program that illustrates three possible ways to interact with 
command in perl.  This is perl, so there are almost certainly others.

#!/usr/bin/perl -Tw

$ENV{PATH}="";  # required due to taint testing

# Method 1: using back-ticks

print "Result:\n";
my $result = `/bin/ls`;

print $result;

print "\n";

# Method 2: using system

my $result2 = system("/bin/ls");

print "\nResult2: $result2\n";

# Method 3: using open

print "\n\nNow using a while loop:\n";
open (LSPIPE, "/bin/ls |");

while (my $line = <LSPIPE>) {
    print $line;
}

---------------------

Note that method 1 gives the entire output in a single variable.  Method 2 
only returns the exit code, perl itself does not see the output of the 
command.  Method 3 allows line by line action on the output of the command.

Cheers,

Rasjid.


-- 

Rasjid Wilcox
Canberra, Australia  UTC + 10
http://www.openminddev.net


More information about the Techtalk mailing list