Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Not able to get the correct output in csv file

Status
Not open for further replies.

choco6

Technical User
Jun 17, 2010
1
IE
Not able to get the correct output in csv file.

Objective: To convert the text file information into a column in csv file.
Problem: Able to get a csv file, but csv file is just copy of txt file.

Expected output: in csv file
case_1
selc
colm
maya
sel[2]
amo
bn
... etc

input file: example.txt
$$. case_1 selc colm maya
$$+ sel[2] amo bn sel
$$+ ace maya case maco


script:

#!/usr/bin/perl

open(FILE, "example.txt") || die "Cannot open input file \n";

open(OUT , " > data.csv") ;
print "Convert example.txt to data.csv\n";
@input = <FILE>;



foreach $name(@input)
{
chop($name);
$name =~ s/$$. //g;
$name =~ s/$$+ //g;
$signal = split(/ /,$name);
print OUT "$signal\n";
}
 
You should use chomp rather than chop these days.

$, + and . have special meanings in regular expressions ("end of line", "one-or-more occurrences" and "any character" respectively), therefore you need to escape them to make them literals, e.g. \$.

split returns a list (a.k.a. array), therefore you can't assign it to a scalar variable. Then in your print statement you need to loop through that list printing each element.

Annihilannic.
 
[ol][li]Your example expected output file is not a CSV file; each entry is on a separate line[/li][li]There is no magic here - if you don't do anything in your code to add the commas in, they won't appear in the output[/li][/ol] Try something like
Perl:
use strict;
use warnings;

while (<>) {
   chomp;   # not chop!
   my @csvline = split;
   shift @csvline;
   print join(',', @csvline), "\n";
}
for an [untested] trivial treatment of CSV separation which doesn't handle string quoting. For anything more complex, use Text::CSV_XS.

Steve

[small]"Every program can be reduced by one instruction, and every program has at least one bug. Therefore, any program can be reduced to one instruction which doesn't work." (Object::perlDesignPatterns)[/small]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top