Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Perl: Sorted union of two arrays (See related posts)

Create a union of two arrays and sort the array.

my @union = array_union_sort(\@first, \@second);

sub array_union_sort {
    my $aa = shift;
    my $bb = shift;
    my %union;
    my $e;
    foreach $e (@$aa) { $union{$e} = 1; }
    foreach $e (@$bb) { $union{$e} = 1; }
    my @union = keys %union;
    @union = sort { $a <=> $b } @union;
    return @union;
}

Comments on this post

towelrod posts on Feb 02, 2007 at 22:09
How about:

sub array_union_sort {
my ($aa, $bb) = @_;
my %union;

foreach my $e (@$aa, @$bb) { $union{$e} = 1; }

my @union = sort keys %union;

return @union;
}

That's without really thinking about whether this is even a good way to do it. Its worth taking half the lines out anyway, right?

You need to create an account or log in to post comments to this site.


Click here to browse all 4861 code snippets

Related Posts