
roolic
User
Apr 6, 2010, 9:10 PM
Post #4 of 9
(12548 views)
|
Re: [kch] parsing rows of data with different lengths
[In reply to]
|
Can't Post
|
|
try following:
open (INFILE, "< a.txt") || die "can not read: $!"; open (OUTFILE, "> out.csv") || die "can not write: $!"; while ( my $string = <INFILE> ){ $string =~ s/^\W+//; # removing garabge in line start $string =~ s/\W+$//; # removing \n\r etc at the end of line # inserting P attribute via "replace" )) # 'MB 1 UL L F UT 100 C 20CT' -> 'MB 1 UL L F UT 100 P C 20CT' $string =~ s/^((?:\w+\s+){7})(?!(?:BX|P)\s+)/$1P /; # the following makes array of strings like # ('MB','1','UL','L','F','UT','100','P','C','20CT') my @attrs = split(/s+/, $str); # if 8th (index is 7 because started from 0) element is 'P' # making it blank according to the requirements $attrs[7] = '' if $attrs[7] eq 'P'; # printing into CSV data file (readable by excel etc) print OUTFILE join(',', @attrs)."\n"; } close INFILE; close OUTFILE; pay an attention that you should not join whole file data into single string because the regex provided will work for first data set only because of '^' (line start) condition in the regex. so it's better to process the file via line by line. if you'd like to process the data (not to store in csv) you can make the array of arrays (2D matrix) the following way: place before while() circle my $data = []; place within while() circle (instead of or in addition to 'print') push @{$data},\@attrs; then you can access the required row and column via $data->[row-1][column-1]
|