Dear list
I want to sort a file which contains the following data.

SUDIP,PQR,OFFICER,15000
DIPAK,ABC,CLERK,7500
CHANDAN,MNP,MANAGER,12000
WASIM,PQR,CLERK,12000
PROTIK,XYZ,MANAGER,14000
DIPAK,XYZ,ADMIN,17000


now I have written a program which will sort the file based on column 1,
column 2 and column 3

use strict;
use warnings;
my $fname="/USERS/anadhikary/test_prog/sort.txt";
open my $DATA,'<',$fname;
my @a = map { [ split "," ] } <$DATA>;
close($DATA);

print map { join ",", @$_ } sort {
       $a->[0] cmp $b->[0] or
       $a->[1] cmp $b->[1] or
       $a->[2] cmp $b->[2]
} @a;

This program works fine. But my question is the columns on which I am
sorting is hard coded. But I want to make the program dynamic.
This file has 4 columns but It can always happen that file has 15 columns
and I need to sort on 8 columns among the 15 columns.
Suppose the user who runs the program is passing the number of column names
as an program argument (for example ./sort.pl 4 5 7 8 12 13 15).

So this condition how can be implemented through this program?

I have tried in the following way
[anadhik...@strawberry test_prog]$ ./sort.pl 1 2 3
the code is as follows(changed part)


for(my $i=0;$i<=$#ARGV;$i++){
        my $val=$ARGV[$i];
        $str_name.="\$a->[".$val."] cmp \$b->[".$val."] or"."\n";;
    }
  $str_name=substr($str_name,0,-3);

print map { join ",", @$_ } sort {
    "$str_name"
}...@a;

## the $str_name prints#####
$a->[1] cmp $b->[1] or
$a->[2] cmp $b->[2] or
$a->[3] cmp $b->[3]
########################
 But when I run the program this gives following error

Sort subroutine didn't return a numeric value at test1.pl line 28

Please Suggest....................

Thanks & Regards
Anirban Adhikary.

Reply via email to