Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: Copy file from one location to another

Tags:

perl

move

This is just a small script I am running to continuous loop to check a directory and move every file that is there. This code works and i am running it in the background processes. But for some reason I am getting the following error: '/home/srvc_ibdcoe_pcdev/Niall_Test/new_dir/..' and '/home/srvc_ibdcoe_pcdev/Niall_Test/perl_files/..' are identical (not copied) at move2.pl line 27

any idea why it is telling me it is identical even though the paths are different?

Many thanks

script below

#!/usr/bin/perl
use diagnostics;
use strict;
use warnings;

use File::Copy;

my $poll_cycle = 10;
my $dest_dir = "/home/srvc_ibdcoe_pcdev/Niall_Test/perl_files";

while (1) {
    sleep $poll_cycle;

    my $dirname = '/home/srvc_ibdcoe_pcdev/Niall_Test/new_dir';

    opendir my $dh, $dirname
        or die "Can't open directory '$dirname' for reading: $!";

    my @files = readdir $dh;
    closedir $dh;

    if ( grep( !/^[.][.]?$/, @files ) > 0 ) {
        print "Dir is not empty\n";

        foreach my $target (@files) {
            # Move file
            move("$dirname/$target", "$dest_dir/$target");

    }
}

}
like image 568
Frostie_the_snowman Avatar asked Jun 15 '16 15:06

Frostie_the_snowman


1 Answers

You need to filter out the special .. and . entries from @files.

#!/usr/bin/perl
use diagnostics;
use strict;
use warnings;

use File::Copy;

my $poll_cycle = 10;
my $dest_dir = "/home/srvc_ibdcoe_pcdev/Niall_Test/perl_files";

while (1) {
    sleep $poll_cycle;

    my $dirname = '/home/srvc_ibdcoe_pcdev/Niall_Test/new_dir';

    opendir my $dh, $dirname
        or die "Can't open directory '$dirname' for reading: $!";

    my @files = grep !/^[.][.]?$/, readdir $dh;
    closedir $dh;

    if (@files) {
        print "Dir is not empty\n";

        foreach my $target (@files) {
            # Move file
            move("$dirname/$target", "$dest_dir/$target");

    }
}

}

The message you see is correct. Both paths resolve to the same directory because of the ..; both resolve to /home/srvc_ibdcoe_pcdev/Niall_Test

.. refers to the directory's parent directory.

like image 178
toolic Avatar answered Sep 27 '22 20:09

toolic