Thursday, October 12, 2006

PERL - Convert Space Delimited to Comma Delimited

Here's some PERL code to convert a list of space-separated or space-delimited variables to comma-separated variables (CSV) or comma-delimited variables.

use strict;

my $indata = $ARGV[0]; # Load a file name from the command line

system "copy $indata $indata-orig"; # Tell DOS to make a copy of file

open(DATA, "<$indata") or die "Couldn't open $indata for reading:$!\n"; my $outdata = "$indata-"; open(OUT, ">$outdata")
or die "Couldn't open $outdata for reading:$!\n";

my @array;

while (<DATA>) # Read the incoming data line by line
{
s/^\s+//; # replace the 1st space with blank (delete first space)
s/(\n)+//; # delete newline at end (probably didn't need to do like this
s/l//i; # for my data I needed to get rid of an "L" in the data
s/(\s)+/,/g; # replace all groups of spaces with a comma

@array = split (',',$_); # Now put each record from the current line into an array
print OUT (join (",", $array[0], $array[1], $array[2], $array[4], $array[6]), "\n"); # then print this array with just the data you want to your output file

# You probably won't have to do the last 2 steps the way I have them. I needed to only bring out a few of the columns. You can just print $_ (which, in PERL, is the most recently affected variable) to your output file.
}
close (DATA) or die "could close $indata: $!\n";
close (OUT) or die "could close $outdata: $!\n";

# I wanted to get rid of junk files and rename my new file the the original filename. You don't have to do this either.
system "del $indata";
system "rename $outdata $indata"
If you have questions, just send me a comment and I'll be glad to answer if I can.

Good afternoon

Donald W. Hasson
http://www.linkedin.com/in/DonaldHasson
http://DonaldHasson.blogspot.com

Monday, October 09, 2006

PERL - Bad File Descriptor

This is an easy one.

I got the error "Couldn't close 0.opt file: Bad file descriptor". As you may know the first part is my language and the part after the colon is the PERL error message "Bad file descriptor". There were a couple of other suggestions for what may be causing this and I've listed their discussion links below. But for me the problem was simply that I had closed the file already in another subroutine. For some reason PERL does not respond with "File already closed" as would be logical.

By the way, I'm on Windows XP using ActivePERL 5.8.8.817.

Other possibly useful links:
http://www.webmasterworld.com/forum13/4039.htm - Bad directory location
http://www.velocityreviews.com/forums/t26003-why-quotbad-file-descriptorquot.html - Bad zip file or non-zip file
http://coding.derkeiler.com/Archive/Perl/perl.beginners/2004-01/1301.html - Troubleshooting suggestions

It also could have to do with permissions on the file.

Good evening

Donald W. Hasson
http://www.linkedin.com/in/DonaldHasson
http://DonaldHasson.blogspot.com