Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Sorting after a split - but not on the first value

Status
Not open for further replies.

RussellDonders

Programmer
Jun 10, 2001
27
GB
Hi,

I need to sort a file alphabetically - but not on the first chars of the line .. I have set up a flat file text delimited database ie

VAL<DELIMITER>VAL2<DELIMITER>VAL3<DELIMITER> etc etc

now I want to be able to sort the file - but not on Val1 - rather alphabetically on VAL2 .. anyone know an easy way to do this ?

What I am doing at the moment is splitting each line into variable names for each of the VALS as i cant see any other way to go about it - but then im stuck.

Thanks,

Russell
 
There are quite a few posts about sorting lists. You might
find something helpful via a keyword search of this forum. If you are new to Tek-Tips, please use descriptive titles, check the FAQs,
and beware the evil typo.
 
One way to do this:
Code:
$delim = &quot;:&quot;;
$field = 2;
$file  = &quot;test.file&quot;;

open( SORT_PIPE, &quot;sort -t $delim -k ${field}n $file | &quot; ) or die;

while( <SORT_PIPE> ) {
    print;
}
close SORT_PIPE;
Another way:
Code:
$delim = &quot;:&quot;;
$field = 2;
$file  = &quot;test.file&quot;;

open( FILE, $file ) or die;

@lines = sort sub {
    $aval = (split($delim,$a))[$field-1];
    $bval = (split($delim,$b))[$field-1];
    return $aval <=> $bval;
}, <FILE>;

close FILE;

print @lines;
The first relies on the UNIX sort command to do the hard work, whilst the second uses pure perl. Cheers, Neil :)
 
Just in case you are wondering where [tt]$a[/tt] and [tt]$b[/tt] come from, the [tt]perlfunc[/tt] man pages states:
Code:
sort SUBNAME LIST

If SUBNAME is specified, it gives the name of a subroutine that returns an integer less than, equal to, or greater than 0, depending on how the elements of the array are to be ordered.
In place of a SUBNAME, you can provide a BLOCK as an anonymous, in-line sort subroutine.
In the interests of efficiency the normal calling code for subroutines is bypassed, with the following effects: the subroutine may not be a recursive subroutine, and the two elements to be compared are passed into the subroutine not via @_ but as the package global variables $a and $b. They are passed by reference, so don't modify $a and $b.  And don't try to declare them as lexicals either.
Hope this explains things a little more clearly.
Cheers, Neil s-)

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top