Quantcast
Channel: UNIX and Linux Forums
Viewing all articles
Browse latest Browse all 16232

Insert text line to specific location CSV

$
0
0
In Perl. ***edited question below***

Hey all, I am teaching myself some simple CSV file manipulation and have become a little stuck. Say I have the following layout in the CSV file:

Code:

age,name,location
Is it possible to INSERT data into the CSV into the correct age order. For example, if I had the following data:

Code:

#appending the CSV line by line, not all at once
>>10,Jim,London
>>8,Jon,Paris
>>21,Jen,Rome
>>17,Bob,Washington

It would go in the CSV file in age order as follows (youngest to oldest):

Code:

8,Jon,Paris
10,Jim,London
17,Bob,Washington
21,Jen,Rome

I have a problem in that I don't have access to the useful Text::CSV library, so any solutions that do not involve an import would be a massive bonus (it doesn't matter if it's sloppy/inefficient as it's purely for educational purposes)

Thanks for your time.

---------- Post updated at 07:19 PM ---------- Previous update was at 04:17 PM ----------

Ok, so I've given up hope that it's possible to do what I want. Instead, I'm just going to sort the details on the fly; I'm still having some problems though. I've pieced together this sorting algorithm but it's only printing out memory locations (E.g: ARRAY(0x6a33e10))

Code:

    my @data;
    my @sorted;
    open FH, "<details.csv" || die ("Can't open details.csv");
   
    while(<FH>) {
        chomp;
        push @data, [split ',', $_]; #split the line
        @sorted = sort { $b->[0] <=> $a->[0] } @data; #sort based on age
        print "$sorted[0]\t$sorted[1]\t$sorted[2]\n";
    }
   
    close FH;


Viewing all articles
Browse latest Browse all 16232

Trending Articles