Chapter 19. Controlling Other Programs

Sometimes you need to ask other programs to do some work for you. The Perl family of languages has been known as the “duct tape of the internet.” Kicking off a well-known, stable, existing program can be easier and faster than reimplementing it yourself. This chapter shows many ways to start and control external programs to bend them to your will.

Quick and Easy

The shell routine is a quick way to run an external command or program. It takes the argument and runs it in the shell as if you had typed it out yourself. This example uses a Unix-like shell command to list all of the files:

shell( 'ls -l' );

If you were on Windows you’d use a different command. There’s an implicit cmd /c in front of your command:

shell( 'dir' );   # actually cmd /c dir

The output from this command will go to the same place that your program’s output will go (as long as you haven’t lexically redirected standard output or error to something else).

You can choose between the commands by inspecting the $*DISTRO variable. The Distro object has an .is-win method that returns True if it thinks your program is running on that platform:

my $command = $*DISTRO.is-win ?? 'dir' !! 'ls -l';
shell( $command );
Warning

Be careful with variables as the argument to shell! Be sure you know what’s in them. If a character is special in the shell then it’s special in that value. More on that in a moment.

shell returns a Proc object. When you use that in sink context (where you do nothing with the ...

Get Learning Perl 6 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.