in reply to Re: Strange Error
in thread Strange Error

What would you suggest? Also thank you for the help!

Replies are listed 'Best First'.
Re^3: Strange Error
by kennethk (Abbot) on Jun 07, 2011 at 23:25 UTC
    If I wrote the code, it might look more like (IMHO, YMMV):

    #!perl -w use strict; my $dir = 'C:\\some_directory'; my $out_file = 'Results.csv'; opendir my $dh, $dir or die "$!"; my @files = grep {/\.txt$/} readdir $dh; for my $file (@files) { open my $in, '<', "$dir/$file" or die "$file: $!"; while (<$in>) { if (/Works: /) { open my $out, '>>', "$dir/$out_file" or die "$out_file: $! +"; print $out substr($_, 20) } } }

    Elements of the above of note:

    1. I've added warnings and strict since I have found it catches a lot of would-be mistakes. See Use strict warnings and diagnostics or die (or The strictures, according to Seuss).

    2. I abstracted string constants to the head of the script, to avoid 1-off typos and make strict to more work for me.

    3. I swapped from barewords to indirect file handles. These have a number of benefits, including automatically closing themselves when they go out of scope and again leveraging strict to protect against 1-off typos. Note that since barewords are globals, your output file is always open once the first edit occurs, whereas mine is closed after every iteration. See Indirect Filehandles for more details.

    4. I swapped to a regular expression that literally translates as 'ends with .txt'. Obviously this may not be your intended file set, but seemed to be what you meant.

    5. I moved from a local @ARGV = @files; while (<>) { construct to explicit nested loops with an explicit open. This admittedly increases the character count; however it improves the legibility, the quality of the error messages and avoids a potential bug. As <> will start processing STDIN if fed an empty @ARGV (see I/O Operators), your script would strangely hang if your target directory had no .txt files.

    6. Lastly, I optimized away some of your inner-loop variables since they are never really used.

    There a couple possible variations on the above themes. For example, in practice instead of the grep I'd probably skip undesirable files with Loop Control. I'd probably also scope the output file outside the loop, so I only open it once. But, to my eye, those are minor.