9

I'm trying to write a utility that will go through a file that would look like this:

# Directory | file name | action | # of days without modification to the file for the command to take action
/work/test/|a*|delete|1
/work/test/|b*|compress|0
/work/test/|c*|compress|1

My script will go through the file deciding if, for example, there are files under /work/test/ that start with 'a' that haven't been modified in the last 1 days, and if so, it would delete them.

For this, I use the find command. Example:

my $command = "find " . $values[0] . $values[1] . " -mtime +" . $values[3] . " -delete ;\n";
system ($command);

But, I've been asked to retrieve the return code for each step to verify that the every step worked fine.

Now, I know that system() returns the return code, and the backticks return the output. But, how can I get both?

1
  • 1
    I would use File::Find, File::Finder, File::Find::Rule, or similar instead of find. That will allow you to check the success of each individual unlink instead of the success of the entire find command. Commented Oct 1, 2015 at 15:12

2 Answers 2

15

After backticks are run, the return code is available in $?.

$?

The status returned by the last pipe close, backtick (``) command, successful call to wait() or waitpid(), or from the system() operator. This is just the 16-bit status word returned by the traditional Unix wait() system call (or else is made up to look like it).

$output = `$some_command`;
print "Output of $some_command was '$output'.\n";
print "Exit code of $some_command was $?\n";
Sign up to request clarification or add additional context in comments.

3 Comments

Tip: All of system, readpipe (backticks), wait and waitpid set $?.
Also note - it won't necessarily be the return code of the command - you may need to bit shift it.
The documentation for system shows how to extra the different values from $?.
3

The universal solution for backticks, system(), etc is to use the ${^CHILD_ERROR_NATIVE} variable. See the perlvar perldoc: http://perldoc.perl.org/perlvar.html#%24%7b%5eCHILD_ERROR_NATIVE%7d

${^CHILD_ERROR_NATIVE} The native status returned by the last pipe close, backtick (`` ) command, successful call to wait() or waitpid(), or from the system() operator. On POSIX-like systems this value can be decoded with the WIFEXITED, WEXITSTATUS, WIFSIGNALED, WTERMSIG, WIFSTOPPED, WSTOPSIG and WIFCONTINUED functions provided by the POSIX module.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.