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?

coconut
  • 1,074
  • 4
  • 12
  • 30
  • 1
    I would use [File::Find](http://perldoc.perl.org/File/Find.html), [File::Finder](https://metacpan.org/pod/File::Finder), [File::Find::Rule](https://metacpan.org/pod/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. – ThisSuitIsBlackNot Oct 01 '15 at 15:12

2 Answers2

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";
Community
  • 1
  • 1
mob
  • 117,087
  • 18
  • 149
  • 283
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.

Andrew Yochum
  • 1,056
  • 8
  • 13
  • [Introduced in perl 5.8.9](https://metacpan.org/pod/perl589delta#New-internal-variables) – mob Oct 01 '15 at 15:04