Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I have been trying to use the following code to sort data from a text file and print it in order alphabetically, only it won't work and I don't understand why !! any help appreciated.

open(INF,"file.txt") || print "Cannot open file\n"; @data= <INF>; close(INF); @sortdata = sort { $a <=> $b } (@data); foreach $i (@sortdata) { # Print stuff }

Edited by Chady -- added code tags.

Replies are listed 'Best First'.
Re: Sorting data problem
by sachmet (Scribe) on Dec 30, 2004 at 05:25 UTC
    <=> is a numeric comparison operator. Use cmp instead, which sorts the strings alphabetically. If case is not important, use { lc($a) cmp lc($b) } for your sort.
Re: Sorting data problem
by davido (Cardinal) on Dec 30, 2004 at 05:27 UTC

    Just make a change to the sort line:

    @sortdata = sort { $a cmp $b } @data;

    The thing is, the <=> operator is for numeric comparisons, and the cmp operator is for string comparisons. See perlop for details on those operators.


    Dave

Re: Sorting data problem
by Errto (Vicar) on Dec 30, 2004 at 05:29 UTC
    Well, I don't know what you mean by "won't work" since you don't give us any sample input or output. But I did notice one problem in your code. You say you want to sort it alphabetically. Therefore instead of
    @sortdata = sort { $a <=> $b } (@data);
    you should have
    @sortdata = sort { $a cmp $b } (@data);
    or even simply
    @sortdata = sort @data;
    The reason is that <=> compares two values numerically whereas cmp compares them alphabetically. This is the default behavior for sort, though.
Re: Sorting data problem
by gopalr (Priest) on Dec 30, 2004 at 05:50 UTC

    Hi,

    while sorting follow the below:

    <=> for Numeric

    cmp for String

    @data= <DATA>; print @sortdata = sort { lc($a) cmp lc($b) } (@data); __DATA__ Orange 99 Grape grape 22 Apple 2 Lemon Orange
Re: Sorting data problem
by r34d0nl1 (Pilgrim) on Dec 30, 2004 at 10:31 UTC
    Hi. I hope that you could sort your text already, but another place to look for information would be
    here - (Perlmonks Q&A - Sorting).
    Another way to find more information about the sorting function is reading the on-line documentation:
    perldoc -f sort and perldoc -q sort
    After reading these docs you will know a lot about sorting.
    I hope it may help you; see ya
Re: Sorting data problem
by Anonymous Monk on Jan 03, 2005 at 02:22 UTC
    THANKYOU MONKS, you are truly wise and I kneel before thee, cheers darren