There are several ways to run an external program in Perl 6, let’s take a look at each way in turn.
Shell is used to pass an expression to the system shell. The shell function invokes the system shell and passes a string argument to it. The return value of `shell` is the exit code of the program:
my $exit_code = shell 'echo "Hello, World!"'; say $exit_code; # 0 == success
If you want redirects, pipes, globs and other shell features to work in your command lines, this is the way to go.
Run is used to execute a program. The run function accepts a stringified program name and optional list of arguments to pass to the external program. Like shell, the return value is the exit code of the program:
my $exit_code = run 'echo', 'Hello, World!'; say $exit_code; # 0 == success
What if you wanted to capture the output of a command, rather than just know if the command was executed successfully or not? Just use a quoting operator “q” and “qq” with the “:x” adverb to execute an expression:
my $message = q:x/echo "Hello, World!"/; say $message; # Hello, World!
If you want to interpolate the expression, use qq:
my $audience = 'Everyone'; my $message = qq:x/echo "Hello, $audience!"/; say $message; # Hello, Everyone!
With quoting mechanisms in Perl 6, the colon is optional for the first adverb so they can be slightly shortened as “qx” and “qqx”.
You’re not limited to slurping results into a single scalar either. Split strings into a list:
# get a list of paths (also see %*ENV) my @env_path = qx/echo $PATH/.split(':'); # Unix-based systems my @env_path = qx/echo %PATH%/.split(';'); # Windows version
Or read a program’s output into an array of lines:
my @commit_results = qqx/git commit -am "$message"/.lines;
Or extract a particular value from tabular data:
# requires "free" program my $free_memory_mb = qx/free -m/.lines.words
These examples just scratch the surface of what’s possible, but they should give you enough to get started any time you need to run an external program. Give them a shot!