Running External Commands with system and Backticks
After a user
had created a bunch of student and leader pages, I wanted him to be
able to run the make_cf.plx
script, which re-creates all the links at
the bottom of all the pages, without my having to do it for him. For
that reason, I created the Regenerate Site
Links
choice on the default page delivered by
make_page.cgi
. Let’s look now at what
happens when the
®enerate_site_links
subroutine is invoked.
eval { system('./make_cf.plx') == 0 or die $? };
This looks pretty scary, but it’s not so bad once we pick it
apart. As usual, we’ll start on the inside of the statement and
work our way out. First comes
system('./make_cf.plx')
. This uses the
system
function to have our script start up a
separate process and run the function’s argument in that
process. Our script will wait for that other process to finish, then
continue on. This is a lot like running an external command inside
backticks
(`
), except that backticks return the output of
that external command so that we can capture it into our program and
do interesting things with it. system
just runs
the external command without returning its output.
It is important to check that nothing went wrong when the external
command ran, which is what that == 0 or die $?
part is doing. Unlike the way we normally check for success or
failure in a Perl function, where the function returns a true value
for success and a false value for failure, the
system
function does just the opposite. ...
Get Perl for Web Site Management 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.