I had to write a csv sorting code for which I used the following code :
foreach(@files){
if(/\.csv$/i) { # if the filename has .csv at the end
push(@csvfiles,$_);
}
}
foreach(@csvfiles) {
$csvfile=$_;
open(hanr, "D:\\stock\\".$csvfile)or die"error $!\n"; # read handler
open(hanw , ">D:\\stock\\sorted".$csvfile) or die"error $! \n"; # write handler for creating new sorted files
@lines=();
@lines=<hanr>;
foreach $line (@lines){
chomp $line;
$count++;
next unless $count; # skip header i.e the first line containing stock details
my $row;
@$row = split(/,/, $line );
push @$sheet2 , $row;
}
foreach my $row (
sort { $a->[0] cmp $b->[0] || $a->[1] cmp $b->[1] } @$sheet2
) # sorting based on date ,then stockcode
{
chomp $row;
print hanw join (',', @$row ),"\n";
}
@$sheet2 = ();
$count = -1;
close(hanw);
close(hanr);
}
However I do not understand what @$row is ..also I understand sorting a normal array @sheet2 comparing column 0 and 1 ..but if someone would explain the whole thing it would be wonderful:
@$row = split(/,/, $line );
push @$sheet2 , $row;
}
foreach my $row ( sort {$a->[0] cmp $b->[0] || $a->[1] cmp $b->[1]} @$sheet2 )
{
*print hanw join (',', @$row ),"\n";
}