[Techtalk] using shell commands in perl scripts

Kai MacTane kmactane at GothPunk.com
Sun May 25 09:51:21 EST 2003

At 5/25/03 12:06 AM , Rasjid Wilcox wrote:
>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.

A quick note: Perl has built-in commands for rm and mkdir, as well as some 
other standard file-handling utilities such as chown, chmod and mv. The 
names are as follows:

Shell     Perl
chmod     chmod
chown     chown
mkdir     mkdir
mv        rename
rm        unlink

These will generally run a bit more quickly and efficiently than a shell 
escape, since they don't have the overhead of spawning a child process.

># Method 1: using back-ticks
>print "Result:\n";
>my $result = `/bin/ls`;
>print $result;
>Note that method 1 gives the entire output in a single variable.

You could also do:

my @result = `/bin/ls`;

which would put each line of output from ls into its own element in the 
@result array. You could then work through that array with a "while 
(@array)" loop, or even grab just the things you need with Perl's built-in 
grep() function. In essence, this would give you the power and flexibility 
of Rasjid's method 3 without needing to use open() and a pipe -- although 
doing so is not a worry to experienced Perl programmers.

Alternatively, you can get a listing of all files in a directory without 
involving /bin/ls at all by using Perl's opendir, readdir, and closedir 
commands. If you need the sort of information that ls -l would give you, 
you can add Perl's stat() function.

                                                 --Kai MacTane
"Friends of science and sensuality,
  They seek the silence and the horror of the shadows..."
                                                 --Charles Baudelaire,

More information about the Techtalk mailing list