Operating System - Linux
1752808 Members
5788 Online
108789 Solutions
New Discussion

Perl Script filter & copy file

 
SOLVED
Go to solution
Sasirekha
Occasional Contributor

Perl Script filter & copy file

Hi,
I need to write a Perl script that takes a directory name as its argument, creates a new sub-directory called executables within it, then scans the directory and all its sub-directories looking for executables and moves them into the new sub-directory.

I tried the below so far it create folder but could not filter & copy...

use File::Copy;
print "Enter the directory name in which you need to check for files\n";
chomp(my $dir = );

chdir $dir or die "Can't chdir to '$dir': $!";

opendir $dir,"." or die "Can't opendir '$dir': $!";
foreach (readdir $dir)
{
next if $_ =~ /^\./;
if($_ != 'executable')
{
mkdir "executable", 0755 or warn "Cannot make executable directory: $!";
if (-x $_){
copy("$_", "executable") or die "Can't copy '$_' to 'executable': $!\n" and print "copied $_ into executable file\n";}
}
if($_ != 'graphics')
{
mkdir "graphics" or warn "Cannot make graphics directory: $!";
if($_ == "*.jpg")
{
copy("$_", "graphics") or die "Can't copy '$_' to 'graphics': $!\n" and print "copied $_ into graphics file\n";
}
}
}
closedir $dir;

1 REPLY 1
H.Merijn Brand (procura
Honored Contributor
Solution

Re: Perl Script filter & copy file

1. Use File::Find ?
2. Use ne/eq instead of ==/!= if comparing strings
3. Use patterm matches instead of !+ "*.jpg"

This recurses into subfolders with File::Find, and fixes all your errors. Take from it what you need

--8<---
use strict;
use warnings;

use File::Find;
use File::Copy;

print "Enter the directory name in which you need to check for files\n";
chomp (my $dir = );

chdir $dir or die "Can't chdir to '$dir': $!\n";

find (sub {
m/^\./ and return;
if ($_ ne 'executable') { # Here was your error. != is numeric comparison
mkdir "executable", 0755 or warn "Cannot make executable directory: $!";
if (-x $_) {
# Specify full target here, and do not double-quote $_: n ot needed
copy ($_, "executable/$_") or die "Can't copy '$_' to 'executable': $!\n";
print "copied $_ into executable file\n";
}
}
if ($_ ne "graphics") { # != vs ne again
mkdir "graphics" or warn "Cannot make graphics directory: $!";
if (m/\.jpg$/) { # $_ == "*.jpg" is unexplainable wrong. Not numeric, and no patter match
copy ($_, "graphics/$_") or die "Can't copy '$_' to 'graphics': $!\n";
print "copied $_ into graphics file\n";
}
}
}, $dir);
-->8---

Enjoy, Have FUN! H.Merijn
Enjoy, Have FUN! H.Merijn