I recently wanted to sort an array, with the sort order being sorted words beginning with a lowercase letter, followed by sorted words beginning with an uppercase letter. The following code does what I want, but was wondering if there is a "niftier" way?
Then I got started thinking on how to arbtrarily define the order by another array. I found the follwing snippet, but it only works for "single letters, not words. It seems it should be easy enough to extend it to words, but the solution eludes me, and I've resorted to using my first method above.#!/usr/bin/perl use strict; use warnings; my @needs_sorting = qw(Psdgs ldfgs Esdds aSdg Sgsdfs esdf sgfsdfg Osgr + T); print @needs_sorting,"\n"; my @lc = sort (grep{substr($_,0,1) eq lc(substr($_,0,1)) }@needs_sorti +ng); my @uc = sort (grep{substr($_,0,1) eq uc(substr($_,0,1)) }@needs_sorti +ng); print "@lc\n"; print "@uc\n"; push @lc,@uc; print join ',', @lc,"\n";
So how would I modify the above code to say sort words by the first letter, if the criteria was complex like:#!/usr/bin/perl use strict; use warnings; my @sorted = ("a" .. "z", "A" .. "Z"); my @needs_sorting = ( qw (P l E a S e s O r T) ); my %S; @S{@needs_sorting} = (); my @is_sorted = grep { exists $S{$_} } @sorted; print join "|",@is_sorted;
As in:my @sorted = ('a' .. 'm','n' .. 'z','X' .. 'Z','A' .. 'W');
#!/usr/bin/perl use strict; use warnings; #not working my @sorted = ('a' .. 'm','n' .. 'z','X' .. 'Z','A' .. 'W'); my @needs_sorting = ( qw (Psdf lPik Easd aKwe SSdf eqwer scfgh Oegb rq +wer T) ); my %S; @S{@needs_sorting} = (); my @is_sorted = grep { ?????? $S{$_} } @sorted; print join "|",@is_sorted;
In reply to criteria based array sorting by zentara
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |