
Jasmine
Administrator
May 9, 2000, 9:20 AM
Post #4 of 4
(344 views)
|
|
Re: Getting multiple strings into an array
[In reply to]
|
Can't Post
|
|
Actually, that won't work because @names will be reassigned eash time the loop repeats, giving you only the last element the loop works with. Because you want sorted results, you should toss the sorted keys into an array first, then loop through the array. This is because you need to get the order before looping through it. (it can't loop and sort simultaneously to my knowledge) You have two sorting options, <=> and cmp <=> is the numeric sorting operator cmp is the text sorting operator If you choose to sort your keys using cmp, like so: my @keys = sort {$a cmp $b} keys %fields; print join "\n",@keys; The result would be in this order: topic1 topic10 topic11 topic2 topic3 Why is 10 after 1 and before 2? Because when you do a textual sort, numbers are treated "asciibetically", meaning that 10 is "less than" 2. Now let's look at what happens if you use <=>, the numeric operator. my @keys = sort {$a <=> $b} keys %fields; print join "\n",@keys; Will print: topic10 topic1 topic11 topic2 topic3 Which is still not what you wanted, because the text (topic) appears before the number. If you swap the location of the number and the word "topic" (or remove the word "topic" altogether"), you will get what you need: $fields{'2topic'} = "Ann"; $fields{'1topic'} = "Jack"; $fields{'3topic'} = "Carl"; #... $fields{'11topic'} = "Mike"; $fields{'10topic'} = "Mary"; my @keys = sort {$a <=> $b} keys %fields; print join "\n",@keys; This will print in this order: 1topic 2topic 3topic 10topic 11topic Now that your order is in @keys, you can loop through this array and append a new array with the values: foreach (@keys) { push (@names,$fields{$_}); # $_ is the key here; $fields{$_} is the value } By using the "push" function, you are appending the @names array with the value while maintaining the same order as @keys. Hope this helps!
|