DZone 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

Snippets has posted 5883 posts at DZone. View Full User Profile

Perl: Sorted Union Of Two Arrays

  • submit to reddit
        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;


Snippets Manager replied on Fri, 2007/02/02 - 10:03pm

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?