sort array of string with tab separated items

Discussion in 'Perl Misc' started by joe, Jun 16, 2009.

  1. joe

    joe Guest

    Hello I have an array of a string of items separated by a tab.
    Something like this
    "country\tfirstname\taddress\tsomethingelse"
    Is there a way to sort the array by one of these fields? or even
    harder to sort by country and then by firstname?
    If not Ill simply re arange the items and sort it Thanks.
     
    joe, Jun 16, 2009
    #1
    1. Advertising

  2. joe <> wrote:
    >Hello I have an array of a string of items separated by a tab.
    >Something like this
    >"country\tfirstname\taddress\tsomethingelse"
    >Is there a way to sort the array by one of these fields? or even
    >harder to sort by country and then by firstname?
    >If not Ill simply re arange the items and sort it Thanks.


    Trivial.
    Use the standard sort() function, and supply your own comparison
    function, which in turn split()s each argument into the four components
    and compares the ones you are interested in.

    While a Schwartzian Transformation may gain you some speed it's not
    really necessary unless your data set is very large and you run into
    actual time constraints.

    jue
     
    Jürgen Exner, Jun 16, 2009
    #2
    1. Advertising

  3. joe

    ace Guest

    joe wrote:
    > Hello I have an array of a string of items separated by a tab.
    > Something like this
    > "country\tfirstname\taddress\tsomethingelse"
    > Is there a way to sort the array by one of these fields? or even
    > harder to sort by country and then by firstname?
    > If not Ill simply re arange the items and sort it Thanks.


    my @sorted =
    map $_->{line},
    sort {
    $a->{country} cmp $b->{country}
    ||
    $a->{firstname} cmp $b->{firstname}
    }
    map {
    my %h = (line => $_);
    @h{qw/country firstname /} = split /\t/, $_, 2;
    \%h;
    }
    @array_of_string;

    For greater efficiency use array instead of %h hash.
     
    ace, Jun 16, 2009
    #3
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Peter Rilling

    Array to a comma Separated String

    Peter Rilling, Jul 8, 2004, in forum: ASP .Net
    Replies:
    3
    Views:
    507
  2. Martijn van Exel

    WebService output > Tab-separated text?

    Martijn van Exel, Nov 2, 2004, in forum: XML
    Replies:
    1
    Views:
    433
    Joris Gillis
    Nov 3, 2004
  3. Cliff  Martin

    Parsing tab separated file

    Cliff Martin, Jan 31, 2007, in forum: C++
    Replies:
    1
    Views:
    332
    rossum
    Jan 31, 2007
  4. per
    Replies:
    2
    Views:
    621
  5. Replies:
    4
    Views:
    245
    Tom Werner
    Jul 21, 2006
Loading...

Share This Page