How to sort lines in an array?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Anja Friedrich

    How to sort lines in an array?

    Hi all,

    I have another question. I have an array sorted like this:
    small_motif_a 1853 1863
    small_motif_a 1970 1980
    small_motif_a 1971 1981
    small_motif_b 789 799
    small_motif_b 882 892
    small_motif_b 1181 1191
    small_motif_b 1193 1203
    small_motif_b 1264 1274
    and so on

    now I want to sort it ascending. I tried it with this code:
    Code:
    #!/usr/bin/perl -w
    use strict;
    use Bio::Perl;
    
    my @var;
    my @lines;
    my @sort_col;
    @sort_col=();
    @lines=();
    @var=();
    my $column;
    my $varfilename;
    
    print "Enter the filename of your input file with the variants:= ";		
    chomp ($varfilename=<STDIN>);
    open (VARINPUT,'<',$varfilename) or die ("$varfilename Can not open file\n");
    @var=<VARINPUT>;
    #print @var;
    			
    $column=1; 
    while(<VARINPUT>) 
    { 
     s/\r?\n//; 
     @var=split /\t/, $_; 
     push @sort_col, $var[$column]; 
     push @lines, "$_\n"; 
    } 
    @lines=sort {$sort_col[$b] <=> $sort_col[$c] } @lines;
    warn "\nSorted $. lines in ascending order, based on numerical values in column $column\n\n"; 
    print @lines [sort { $sort_col[$b] <=> $sort_col[$c] } 0..$#sort_col];
    print "@lines\n";
    but it is not working.
    Anyone an idea please?
  • toolic
    Recognized Expert New Member
    • Sep 2009
    • 70

    #2
    You should use $a and $b (not $b and $c) in your sort block. I'm surprised your code compiles without errors with use strict.

    Comment

    • Anja Friedrich

      #3
      Well, I had it first with $a and $b but I thought it refers to the columns, and I need to sort the 2nd and 3rd. I don't get an output. Only the message that it was sorted

      Comment

      • chorny
        Recognized Expert New Member
        • Jan 2008
        • 80

        #4
        In first sort you are trying to access array with strings from file as indexes.

        Comment

        Working...