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

i have a script that moves files around a directory structure based on entries in a database and the file name. The problem is that, if it encounters one file that it cannot move, it stopes execution.How do i force it to leave that file and move on to the next file?

the script is here.728050

Could anyone help me optimise it?

UPDATE: am working on condensing the code.sorry for any inconvinience.I will condense and put it in my question.

foreach my $file (@files){ ...#perform parsing and lookup from database to determine where to +place the file. if (!-e $dir){ mkdir(...) or die("..."); } move(...) or die("..."); ... } sub on_error(){ ##call a batch file }
i would like to know if there is a way to handle errors such that the program does its best to continue without interuppting the process and id it cannot, then it calls the on_error subroutine which just calls an external batch file Thanks - Sandhya
  • Comment on how do i force a script to execute even when it encounters an error?
  • Download Code

Replies are listed 'Best First'.
Re: how do i force a script to execute even when it encounters an error?
by ikegami (Patriarch) on Feb 23, 2009 at 17:00 UTC
    Your code is basically
    foreach my $file (@files){ ... mkdir(...) or die("..."); move(...) or die("..."); ... }
    So change it to
    foreach my $file (@files){ ... mkdir(...) or do { warn("..."); next }; move(...) or do { warn("..."); next }; ... }

    or

    foreach my $file (@files){ if (!eval { ... mkdir(...) or die("..."); move(...) or die("..."); ... 1; }) { die("Error processing file $file: $@"); } }

    Update: Better yet, use a sub!

    sub process_file { my ($file) = @_; ... mkdir(...) or die("..."); move(...) or die("..."); ... } foreach my $file (@files){ if (!eval { process_file($file); 1 }) { die("Error processing file $file: $@"); } }
Re: how do i force a script to execute even when it encounters an error?
by Corion (Patriarch) on Feb 23, 2009 at 16:54 UTC

    Please reduce the script on smanicka's scratchpad and post it here. When you change your scratchpad, the nodes here would lose their context. Also, as has already been told you in the CB, why not wrap the potentially dieing code in an eval statement?