zentara has asked for the wisdom of the Perl Monks concerning the following question:
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;
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: criteria based array sorting
by broquaint (Abbot) on Feb 12, 2004 at 18:01 UTC | |
by hardburn (Abbot) on Feb 12, 2004 at 20:34 UTC | |
by Limbic~Region (Chancellor) on Feb 12, 2004 at 20:41 UTC | |
by jdporter (Paladin) on Feb 13, 2004 at 06:09 UTC | |
Re: criteria based array sorting
by Limbic~Region (Chancellor) on Feb 12, 2004 at 17:51 UTC | |
Re: criteria based array sorting
by Roy Johnson (Monsignor) on Feb 12, 2004 at 18:04 UTC | |
Re: criteria based array sorting
by Not_a_Number (Prior) on Feb 12, 2004 at 18:45 UTC | |
Re: criteria based array sorting
by hv (Prior) on Feb 12, 2004 at 19:10 UTC | |
by Roy Johnson (Monsignor) on Feb 12, 2004 at 21:00 UTC | |
Re: criteria based array sorting
by zentara (Cardinal) on Feb 13, 2004 at 17:28 UTC | |
by Willard B. Trophy (Hermit) on Feb 13, 2004 at 18:23 UTC | |
by Limbic~Region (Chancellor) on Feb 13, 2004 at 21:13 UTC | |
Re: criteria based array sorting
by zentara (Cardinal) on Feb 12, 2004 at 22:28 UTC |