in reply to Re: Import comma delimited file into an array
in thread Import comma delimited file into an array

I updated my code again. You will probably see what I'm trying to do. Let me know if there is a better or more efficient way of doing it.
use File::Glob; my @files = glob("C:/Wire/*.csv"); open OUTPUT, ">C:/Wire/WO.txt"; foreach my $x (@files) { open FILE, $x; while (<FILE>) { my @row = split(/,/, $_); next if (substr($_,0,5) =~ /Debit/) ; print "{1100}02P N" . $row[6] . "{1110}" . "{1120}" . "{1510}" . " +{1520}" . "{3320}" . "{3400}" . "{3600}" . "{4320}" . "{5000}" . "\n"; print OUTPUT "{1100}02P N" . $row[6] . "{1110}" . "{1120}" . "{151 +0}" . "{1520}" . "{3320}" . "{3400}" . "{3600}" . "{4320}" . "{5000}" . "\n" } }

Replies are listed 'Best First'.
Re^3: Import comma delimited file into an array
by toolic (Bishop) on Nov 19, 2008 at 00:44 UTC
    Here are some improvements I would make:
    • use warnings; use strict;
    • Use lexical filehandles $fh.
    • Use the 3-argument form of open
    • Check the return value of open with die
    • Check for 'Debit' immediately
    • Use eq instead of a regex to check for 'Debit'
    • Just grab the 7th element from the array returned by split
    • Eliminate most of those concatenation operators
    • close the file
    use strict; use warnings; use File::Glob; my @files = glob("C:/Wire/*.csv"); for my $file (@files) { open my $fh, '<', $file or die "can not open file $file: $!"; while (<$fh>) { next if (substr($_,0,5) eq 'Debit'); my $row6 = (split /,/)[6]; print "{1100}02P N", $row6, "{1110}{1120}{1510}{1520}{3320}{3400 +}{3600}{4320}{5000}\n"; } close $fh; }
      Hi toolic! Why close the file, if it was open with lexical filehandle (and should be closed when scope goes away?)
      []s, HTH, Massa (κς,πμ,πλ)
        In this instance, you are probably correct in that there is no need to close the lexical filehandle. However, I do so out of a force of habit, and because I believe it is a good practice. Here is one reason, according to the documentation for close:
        You don't have to close FILEHANDLE if you are immediately going to do another "open" on it, because "open" will close it for you. (See "open".) However, an explicit "close" on an input file resets the line counter ($.), while the implicit close done by "open" does not.

        Also, there is a good discussion on this topic in the book, Perl Best Practices, Chapter 10 (I/O), in the section titled: "Close filehandles explicitly, and as soon as possible".

        close $fh or warn "WHACKO ERROR: CLOSE $file $fh : $file may be corrup +t(incomplete) : $!";
      Thanks your suggestions are extremely helpful which I will implement. Thanks again. Dave