Execing Processes in Perl

Here’s the translation of the Go code to Perl, with explanations in Markdown format suitable for Hugo:

Our example demonstrates how to replace the current process with a new one using Perl’s exec function, which is similar to the classic Unix exec system call.

#!/usr/bin/perl
use strict;
use warnings;

# For our example we'll exec `ls`. Perl doesn't require an
# absolute path to the binary we want to execute, but we'll
# use `which` to find it anyway (probably `/bin/ls`).
my $binary = `which ls`;
chomp($binary);
die "Could not find ls" unless $binary;

# `exec` in Perl can take arguments directly as a list.
# We'll give `ls` a few common arguments. Note that the
# program name is not repeated as the first argument in Perl.
my @args = ('-a', '-l', '-h');

# In Perl, the current environment is automatically passed to
# the new process, so we don't need to explicitly set it.

# Here's the actual `exec` call. If this call is successful,
# the execution of our process will end here and be replaced
# by the `/bin/ls -a -l -h` process. If there is an error,
# exec will return and we can handle it.
exec($binary, @args) or die "exec failed: $!";

# This line will only be reached if exec fails
print "This line will never be printed.\n";

When we run our program, it is replaced by ls:

$ perl execing-processes.pl
total 16
drwxr-xr-x  4 user 136B Oct 3 16:29 .
drwxr-xr-x 91 user 3.0K Oct 3 12:50 ..
-rw-r--r--  1 user 1.3K Oct 3 16:28 execing-processes.pl

Note that Perl, like many Unix-based languages, provides a direct interface to the exec system call. This makes it straightforward to replace the current process with a new one.

Unlike some languages, Perl does offer a classic Unix fork function, which can be used in conjunction with exec to create new processes. However, for many use cases, using system or backticks (`) for command execution, or modules like Proc::Spawn for more complex process management, can be more convenient alternatives to manual forking and exec’ing.