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


I'm doing some (what I think is) more unusual things with some arrays.. and I'm looking to see if there's a more 'elegant' method than what I'm currently using...

I have a 'reference' array that is processed, producing a 'subset' array. Generally, the elements of the 'subset' array are not in the same order as they appear in the 'reference' array... but that's the order I need to do some more processing.

So, I've cobbled together some code that does the job, viz:-

use Data::Dumper; @array = ( "APPLE", "ORANGE", "PEACH", # Use this for the ORDE +R "GRAPE", "BANANA", "PINEAPPLE" ); @subset = ( "PINEAPPLE", "GRAPE", "APPLE" ); # A required subset but + NOT # in the required order @results = (); # The subset with its e +lements in the # same order as the 're +ference' array # ---- Method 1: Using arrays directly @tmp = (); foreach my $check (@subset) { my ($index) = grep { $array[$_] eq $check } 0..$#array; push(@tmp, $index); } @index_list = sort {$a <=> $b} @tmp; # Sort the index values numerica +lly @results = @array[@index_list]; # Slice the index items out of ' +@array' printf("Method 1:\n"); print Dumper(@results); printf("\n"); # ---- Method 2: Using a sub Reset_Order(\@subset, \@array, \@results); printf("Method 2:\n"); print Dumper(@results); printf("\n"); # ========== end mainline ========== # ------------------------------------- # Reset_Order - ... # Uses Globals: # ------------------------------------- sub Reset_Order { my ($small_ref, $large_ref, $res_ref) = @_; my (@tmp); @tmp = (); foreach my $check (@$small_ref) { my ($index) = grep { $$large_ref[$_] eq $check } 0..$#$large_ref +; push(@tmp, $index); } my @index_list = sort {$a <=> $b} @tmp; # Sort the index values nu +merically @$res_ref = @$large_ref[@index_list]; # Slice the index items ou +t of the large array return(1); } # end Reset_Order

...but maybe there's a better way to do it, say, using grep in conjunction with map but I can't vizualize how that might be done -- I'm still not super flash with the 'more clever' ways of using these functions(!)

I would search for something to help me out... but I don't even know how to describe what I'm trying to do(!)

I'd appreciate any suggestions on where to go next...