I wish to sort an array of strings so that the strings wind up in the following order:
@set = ('oneM', 'twoM', 'threeM', 'sixM', 'oneY', 'twoY', 'oldest');
As you may notice, these represent time periods so oneM is the first month, etc. My problem is that I want to sort by the time period, but with the strings as they are I can’t just use ‘sort’, so I created this hash to express how the strings should be ordered:
my %comparison = (
oneM => 1,
twoM => 2,
threeM => 3,
sixM => 6,
oneY => 12,
twoY => 24,
oldest => 25,
);
This I was hoping would make my life easier where I can do something such as:
foreach my $s (@set) {
foreach my $k (%comparison) {
if ($s eq $k) {
something something something
I’m getting the feeling that this is a long winded way of doing things and I wasn’t actually sure how I would actually sort it once I’ve found the equivalent… I think I’m missing my own plot a bit so any help would be appreciated
As requested the expected output would be like how it is shown in @set above. I should have mentioned that the values in @set will be part of that set, but not necessarily all of them and not in the same order.
You’ve choose good strategy in precomputing data to form easy to sort. You can calculate this data right inside sorting itself, but then you’d be wasting time for recalculation each time
sortneeds to compare value, which happens more than once through process. On the other hand, the drawback of cache is, obviously, that you’d need additional memory to store it and it might slow down your sort under low memory condition, despite doing less calculations overall.With your current set up sorting is as easy as:
While if you want to save memory at expense of CPU it’d be:
with separate
calculate_integer_based_on_inputfunction that would convertoneYand the like to12or other corresponding value on the fly or just inline conversion of input to something suitable for sorting.You might also want to check out common idioms for sorting with caching computations, like Schwartzian transform and Guttman Rosler Transform.