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

Hi All, I have written a small perl script to perform copy operation. I have a list of directories which i have to go to and check for a file. I have only a part of the file name. Using this part filename i have to find the file and copy it from there to another directory. How can i achieve this.

Replies are listed 'Best First'.
Re: copy script
by marto (Cardinal) on Mar 25, 2010 at 10:59 UTC

    I'm not sure I understand exactly what you mean, perhaps File::Find is what you're looking for. Perhaps if you show us your existing code, any example input and a better description of the problem we could advise more. Is it similar to your previous question?

Re: copy script
by prasadbabu (Prior) on Mar 25, 2010 at 10:58 UTC

    Hi raghu_shekar,

    Read all the files in an array. Using perlre match the partial filename with the original file name, as per your requirement. Then using copy function, you can copy to the target location.
    For example:

    if ($original_filename =~ /$partial_name/){ // add some more conditions to filter further based on your requiremen +t }

    Prasad

      Hi, I have around 10 different directories which im storing in an array and looping through them and trying to find the file. I am sure that there is only one file with the name.. eg <*activ*>. Any easier way how i can fine this one file on the fly without having to store all the files in an array and looping through them..?
Re: copy script
by kiruthika.bkite (Scribe) on Mar 25, 2010 at 11:29 UTC
    use File::Find; my $command="cp"; my $target="/home/kiruthika/Technical/NEW/"; #Here mention your direct +ory path to where you need to copy the files. my $str; find(\&wanted,(".","..",)); sub wanted() { if(/.*\.txt/)#find the .txt files and copy those into another loca +tion. { $str=$command." ".$_." " .$target; system("$str"); $str=" "; } }

    find() function will call the wanted function for each files in the current directory and as well in the parent directory of the current directory.

    In the wanted function I have checked whether the file is .txt file or not.
    If it is .txt file then I have copied that file into the target directory.

    In find() function ,in the second argument you mention the directories to be searched.

      So you are assuming the cp command is available, calling it via system, you're also assuming that the copy has worked and not bothered to check for errors?. Why not use File::Copy (it's core and portable) and actually check that no error was returned?

Re: copy script
by roboticus (Chancellor) on Mar 25, 2010 at 11:03 UTC