Sort an array by the elements of the second array

Suppose I have two arrays that look like this:

('1', '6', '8', '4', '5') ('a', 'c', 'd', 'f', 'w') 

I want to sort the first array, and the order of the elements in the second array should change the same as the first array, so the order of the two will be as follows:

 ('1', '4', '5', '6', '8') ('a', 'f', 'w', 'c', 'd') 

Any ideas on how to do this in Perl?

+6
source share
3 answers

You need to sort the indices in the array. Like this

 use strict; use warnings; my @aa = qw/ 1 6 8 4 5 /; my @bb = qw/ acdfw /; my @idx = sort { $aa[$a] <=> $aa[$b] } 0 .. $#aa; @aa = @aa[@idx]; @bb = @bb[@idx]; print "@aa\n"; print "@bb\n"; 

Output

 1 4 5 6 8 afwcd 
+10
source

You can use the hash. Use the values ​​from the first array as keys to the values ​​taken from the second array. Then just do foreach my $key ( sort keys %the_hash) { do stuff } . If the key values ​​are not unique, then the hash of the arrays and clicking the values ​​into the hash file are used.

 #! perl use strict; use warnings; my @key_data = ('1', '6', '8', '4', '5', '4', '5'); my @val_data = ('a', 'c', 'd', 'f', 'w', 'z', 'w'); my %the_hash; for ( my $ii=0; $ii<=$#key_data; $ii++) { push @{$the_hash{$key_data[$ii]}}, $val_data[$ii]; } for my $key ( sort keys %the_hash ) { print "key $key\n"; foreach my $val ( @{$the_hash{$key}} ) { print " $val\n"; } } 
+3
source

Borodin's answer is an excellent answer to your question. It seems to me that the structure of your data suggests that a hash can be useful, so here is an example of data binding using a hash and sorting in this way.

 use strict; use warnings; use List::MoreUtils qw(mesh); my @aa = qw/ 1 6 8 4 5 /; my @bb = qw/ acdfw /; my %x = mesh @aa, @bb; print join(" ", sort keys %x), "\n"; print join(" ", @x{sort keys %x}), "\n"; 
+2
source

Source: https://habr.com/ru/post/944360/


All Articles