Insert text line to specific location CSV

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:

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:

#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):

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))

    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;
#!/usr/bin/perl
#

use strict;
use diagnostics;

my @data;
my @sorted_data;
my $csvfile = "details.csv";

open(FH, "<$csvfile") or die "Unable to open $csvfile.\n";
@data = <FH>;
@sorted_data = sort { (split ',', $a)[0] <=> (split ',', $b)[0] } @data;
foreach(@sorted_data) { print; }
close(FH);
exit(0);
1 Like