sort array of string with tab separated items

J

joe

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.
 
J

Jürgen Exner

joe said:
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
 
A

ace

joe said:
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.
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top