Skip to Main Content
Perl Cookbook
book

Perl Cookbook

by Tom Christiansen, Nathan Torkington
August 1998
Intermediate to advanced content levelIntermediate to advanced
800 pages
39h 20m
English
O'Reilly Media, Inc.
Content preview from Perl Cookbook

Replacing the Current Program with a Different One

Problem

You want to replace the running program with another, as when checking parameters and setting up the initial environment before running another program.

Solution

Use the built-in exec function. If exec is called with a single argument containing metacharacters, the shell will be used to run the program:

exec("archive *.data")
    or die "Couldn't replace myself with archive: $!\n";

If you pass exec more than one argument, the shell will not be used:

exec("archive", "accounting.data")
    or die "Couldn't replace myself with archive: $!\n";

If called with a single argument containing no shell metacharacters, the argument will be split on whitespace and then interpreted as though the resulting list had been passed to exec:

exec("archive accounting.data")
    or die "Couldn't replace myself with archive: $!\n";

Discussion

The exec function in Perl is a direct interface to the execlp (2) system call, which replaces the current program with another, leaving the process intact. The program that calls exec gets wiped clean, and its place in the operating system’s process table is taken by the program specified in the arguments to exec. As a result, the new program has the same process ID ($$) as the original program. If the specified program couldn’t be run, exec returns a false value and the original program continues. Be sure to check for this.

If you exec yourself into a different program, neither your END blocks nor any object destructors will ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Perl in a Nutshell

Perl in a Nutshell

Nathan Patwardhan, Ellen Siever, Stephen Spainhour
Perl Best Practices

Perl Best Practices

Damian Conway
Mastering Perl

Mastering Perl

brian d foy
Perl Cookbook, 2nd Edition

Perl Cookbook, 2nd Edition

Tom Christiansen, Nathan Torkington

Publisher Resources

ISBN: 1565922433Supplemental ContentCatalog PageErrata