Link to home
Create AccountLog in
Avatar of new_perl_user

asked on

Suggestion for an issue in perl script


Below is my code where I go to different places and  delete ID's  from that path.

Right now. If it is not able to delete any ID, it is getting stuck there and the script is exiting without further deletion.

Can anyone  please let me know  how to  change the code so that it will record the ID ina log which was not deleted and move further..

y $path1 = "/usr/Files/$id";
my $path2 = "/usr/qa/$id";
my $path3 = " /d/data/$id";

if (-e $path1) {
        push @{$count[1]}, $id;
        system("rm -rf $path1") == 0 or die "rm -rf $path1 failed: $?";

    if ( -e $path2) {
        push @{$count[2]}, $id;
        system("rm -rf $path2") == 0 or die "rm -rf $path2 failed: $?";

    my $tmp = "ssh dev\@ 'ls -d $path3'";
    if ($tmp =~ m{\b$id\b} and $tmp !~ m{cannot\s+access} and $tmp !~ m{no such file}i) {
        push @{$count[3]}, $id;
       system("ssh dev\@ 'rm -rf $path3'") == 0
            or die "rm -rf $path3 failed on remote host: $?";

Open in new window

Avatar of farzanj
Flag of Canada image

You can try:

Instead of system call:
system("rm -rf $path1") == 0 or die "rm -rf $path1 failed: $?";

my @not_deleted;

unlink $path1 or push(@not_deleted, $path1);

Then at the end you can write the contents of @not_deleted into a log file.
Are you deleting files or directories?

If deleting files, then it would be better to use Perl's built-in unlink function instead of the system call to rm.  Then, instead of the die statement, you'd call a sub that logs the filename and error message, or you can add the filename and error message to a hash to be processed later.
unlink $file1 or error_log($file1, $!);

Open in new window

If you're deleting directory trees, then it would be better to use the File::Path module instead of the system call.
# The errors are stored in $error, which is a reference to an array of hashes
remove_tree($path1, $path2, { error => \my $error } );

Open in new window

Avatar of new_perl_user



I am deleting directories  but no the whole tree only a subdirectory  in a directory..
I tried the above suggestion as below but it is not working.

if (-e $path1) {

        remove_tree($path1 , { error=> \my $error});
      print "$error \n";


I removed the directory  it has to delete from the path, but it did not report error  as  "No such file or Directory"
Avatar of FishMonger
Flag of United States of America image

Link to home
Create an account to see this answer
Signing up is free. No credit card required.
Create Account