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

Hello All, I have a number of text files in one directory (directory A). I need to first select files that contains some keywords" from directory A, and then output the selected files to a new directory (directory B). I am new to Perl...couldn't figure it out. below is my code which didn't work.
#!/usr/bin/perl $write_dir="C:\\directoryB"; my @files=<C:/directoryA/*>; foreach $file (@files) { open (FILE,"$file"); while ($line=<FILE>){ print "$file\n" if $line=~/keyword/; } close FILE; }
Thanks a lot!

Replies are listed 'Best First'.
Re: write multiple files to a new directory
by stevieb (Canon) on Oct 23, 2015 at 20:09 UTC

    Welcome to the Monastery, jingmcgill!

    First things first, whenever you post code, input data, or expected output data, please put it into <code></code> tags per Markup in the Monastery. With that out of the way, let's carry on...

    You have some syntax issues with the code you've supplied. The first two lines in your Perl programs should always be use warnings; and use strict;. These two pragmas will catch almost all issues that prevent a program from compiling/running.

    Next, you should always use the three-argument form of open, and catch any errors if they present themselves with a die statement.

    The below example shows everything I've mentioned above in action, and after you've replaced my file paths with your original ones, you should be good to go. Note to actually copy the file(s), I've used the copy() function from the File::Copy module, which is built into the perl core.

    use warnings; use strict; use File::Copy; my $write_dir = 'two/'; my @files = <one/*>; for my $file (@files){ open my $fh, '<', $file or die "can't open file $file for reading!: $!"; my $copy_it = 0; while (my $line = <$fh>){ if ($line =~ /keyword/){ print "$file\n"; $copy_it = 1; last; } } close $fh; if ($copy_it){ copy $file, $write_dir or die "can't copy file $file to $write_dir!: $!"; } }
      Hello, Thank you very much for the help! I will pay attention to those syntax issues in the future.
Re: write multiple files to a new directory
by toolic (Bishop) on Oct 23, 2015 at 20:11 UTC
Re: write multiple files to a new directory
by AnomalousMonk (Archbishop) on Oct 24, 2015 at 11:21 UTC
Re: write multiple files to a new directory
by ww (Archbishop) on Oct 25, 2015 at 12:54 UTC
    1. Where does @files (Ln 6) get populated?
      And, (based on your statement, "I need to first select files that contains (sic) some keywords...")
    2. If @files is supposedly populated by some selection mechanism, what's the selection code look like?