How to parse a text file to csv file using Perl

I am learning Perl and would like to parse a text file to csv file using Perl. I have a loop that generates the following text file:

my $query = "SELECT id, name, age, weight, height, speed, time FROM athletes";
my $results = $db->prepare($query);
$results->execute();

my $data = ();
foreach my $rowRef(@results) {
  my %row;
  my @row = @$rowRef;
  $row{id} = $row[0];
  $row{name} = $row[1];
  $row{age} = $row[2];
  $row{weight} = $row[3];
  $row{height} = $row[4];
  $row{speed} = $row[5];
  $row{time} = $row[6];
  push(@data, {%row}); 
}

for $row(@$data) {
  while(my($key,$value) = each(%$row)) {
    print "${key}=${value}, ";
  }
  print "\n";
}

Text File Output:

name=Mary, id=231, age=38, weight=130, height=5.05, speed=26.233, time=30, 
time=25, name=Jose, age=30, id=638, weight=150, height=6.05, speed=20.233, 
age=40, weight=130, name=Mark, id=369, speed=40.555, height=5.07, time=30 

CSV File Desired Output:

name,age,weight,height,speed,time
Mary,38,130,5.05,26.233,30, 
Jose,30,150,6.05,20.233,25, 
Mark,40,130,5.04,40.555,30

Any good feedback is welcome!



Read more here: https://stackoverflow.com/questions/64868909/how-to-parse-a-text-file-to-csv-file-using-perl

Content Attribution

This content was originally published by Bebe at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: