Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I have successfully backed up my data file using:

copy("applicants.txt","$targetfile") or die "Copy failed: $!";

I have read that copy, or any function, returns 1 upon success, 0 upon failure. I wish to test for success or failure without user resorting to the log file. I would expect something simple like:

if (whatever == 1) { do something; }

I have researched the archive and google without success in answering this. Please respond with code example, as I'm a newbie. Thanks.

Replies are listed 'Best First'.
Re: Testing Return Values
by toolic (Bishop) on Jun 05, 2013 at 15:08 UTC
    use warnings; use strict; use File::Copy qw(copy); if (copy('applicants.txt', $targetfile)) { print "success\n"; } else { print "failure\n"; }

      Got it! Thanks.

Re: Testing Return Values
by davido (Cardinal) on Jun 05, 2013 at 15:20 UTC

    I assume that by saying "any function, returns 1 upon success", you're referring to functions documented in File::Copy, for they're documented to do just that. In general functions that make system calls return Boolean true upon success, and false upon failure. But check the documentation for specific functions if you want to count on "true" being "1".

    Anyway, on to your question. You didn't really explain what it is that you want to do. Your sample code snippet is actually fine, if applied correctly. Here's an example:

    if( copy $source, $dest ) { print "Success!"; } else { warn $!; }

    The logical short circuit operators, "and", "&&", "or", "||", can be used as a shorthand for more formal or explicit control flow syntax. In the example I provided, I used "if(){}". Here's another:

    barf "Green pigs: $!" unless copy $source, $dest;

    I'll leave it to you to implement the barf() function. ;)


    Dave

Re: Testing Return Values
by Anonymous Monk on Jun 05, 2013 at 16:32 UTC

    If you want something that looks like your copy("applicants.txt","$targetfile") or die "Copy failed: $!"; with a  { do_something } block instead of die you could write copy("applicants.txt","$targetfile") or do { do_something }.

    If do_something is a simple statement and not a block, you may even just write copy("applicants.txt","$targetfile") or do_something;