This was a note I made while reading the Perl
Cookbook.   I can't imagine the application which would use it as is, but it does summarize this stuff which does seem to come up all the time.
#!/usr/bin/perl -w
# returns union, intersection and differences of two arrays
# as per sections 14.7 and 14.8 of the Perl Cookbook
# (but does not preserve order!)
# usage:
# ( \@merged, \@common, \@only_a, \@only_b ) = intersets(\@a, \@b)
sub intersets {
my ($a, $b) = @_;
my (%ah, %bh);
@ah{ @$a } = @$a;
@bh{ @$b } = ();
delete @bh{ @$a };
( [ keys %ah, keys %bh ], [ grep defined, delete @ah{ @$b } ],
[ keys %ah ], [ keys %bh ] )
}
my @a = qw(a b c d e);
my @b = qw(b e f g h i);
print "[ @a ], [ @b ]\n
";
my($mrg, $common, $a, $b) = intersets(\@a, \@b);
print "merged: '@$mrg'\ncommon: '@$common'\n";
print "only a: '@$a'\nonly b: '@$b'\n";
=pod
[ a b c d e ], [ b e f g h i ]
merged: 'a b c d e h i f g'
common: 'b e'
only a: 'a c d'
only b: 'h i f g'
=cut
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.