SPUG: Better way to sort POD list-items?
Marc M. Adkins
Perl at Doorways.org
Thu Mar 11 17:02:25 CST 2004
On Friday 12 March 2004 12:33 am, Tim Maher wrote:
> SPUGaholics,
>
> I just found a need to dash off the following script, in order to
> sort the glossary entries of the book I'm working on into
> alphabetical order.
>
> Seems like there should be an easier way!
>
> Anybody got a cleaner technique for associating the item labels
> with their associated data? I think I used to know a trick with
> split() to do that, but if so I sure can't remember it now ...
Not sure what you are asking, but I usually write the first part using splice:
my @chunks = split /(^=item[^\n]*?\n)/m, $_;
my @items = ( );
shift @chunks; # throw away useless header
while (@chunks > 1) {
my ($item, $contents) = splice @chunks, 0, 2;
push @items, "$item$contents";
}
I use this pattern on a daily basis for splitting apart documents.
If you're asking about the sort, you could use:
while (@chunks > 1) {
my ($item, $contents) = splice @chunks, 0, 2;
my ($name) = $item =~ /^=item\s*(.*?)\s*\n/;
push @items, [ $name, "$item$contents" ];
}
and then the sort becomes:
sort { $a->[0] cmp $b->[0] } @items;
I suppose another variant might be:
my @chunks = split /(^=item[^\n]*?\n)/m, $_;
shift @chunks;
my %items = @chunks;
print $_, $items{$_} for sort keys %items;
Though I think that depends on well-formedness of the
=item tags. I would probably use:
my @chunks = split /^=item\s+(.*?)\s*?\n/m, $_;
shift @chunks;
my %items = @chunks;
print "=item $_\n", $items{$_} for sort keys %items;
But I'm probably missing the point.
mma
More information about the spug-list
mailing list