Can this perl shell function be extended to work with any input function?

Consider the following wrapper function, which returns a given function a specified number of times if the function throws (not sure why formatting is unstable):


sub tryit{
    my $fun = shift;
    my $times = shift;
    my @args = @_;
    my $ret;
    do{  
    $times--;
    eval{
        $ret = $fun->(@args);
    };
    if($@){
        print "Error attemping cmd: $@\n";
    }
    else{
         return $ret;
    }
    }while($times > 0);
    return;

}

How can this be expanded so that the return value of the parameter function is properly skipped no matter what value is returned? For example, this function will not process the array correctly. You cannot just return $ fun → (), because the return only returns from the eval block.

+3
source share
2 answers

You can do this with wantarray . (This is also formatting for me, sorry)

sub tryit{
    my $fun = shift;
    my $times = shift;
    my @args = @_;
    my $array_wanted = wantarray;
    my $ret;
    my @ret;
    do{  
    $times--;
    eval{
        if ($array_wanted) {
            @ret = $fun->(@args);
        }
        else {
            $ret = $fun->(@args);
        }
    };
    if($@){
        print "Error attemping cmd: $@\n";
    }
    else{
         if ($array_wanted) {
             return @ret;
         }
         else {
             return $ret;
         }
    }
    }while($times > 0);
    return;

}

, Perl- , .

+5

, Nemo, :

  • .
  • .
  • , STDERR.
  • .
  • .
  • .

wantarray .

sub tryit {
    my $func        = shift;
    my $attempts    = shift;
    my $list_wanted = wantarray;
    my @rv;
    for (2..$attempts) {
        if (eval{
            if ($list_wanted) {
                @rv = $func->(@_);
            } else {
                $rv[0] = $func->(@_);
            }
            1  # No exception
        }) {
            return $list_wanted ? @rv : $rv[0];
        }

        warn($@, "Retrying...\n");
    }

    return $func->(@_);
}

Void void, , , . , .

+6

All Articles