in reply to Array comparison using perl

...and not using any modules:
#!/usr/bin/env perl # use strict; use warnings; my @a1 = (1, 2, 3, 4, 5, 6, 7, 8, 9); my @a2 = (1, 4, 5, 9 ,7); print "\@a1 is (".(join ",", @a1).")\n"; print "\@a2 is (".(join ",", @a2).")\n"; my ($e1, $f); my @a3; for $e1 (@a1) { $f = 0; for (@a2) { if ($e1 eq $_) { $f++; } } unless ($f) { push @a3, $e1 } } print "\@a3 is (".(join ",", @a3).")\n";

Replies are listed 'Best First'.
Re^2: Array comparison using perl
by GrandFather (Saint) on Dec 21, 2010 at 20:18 UTC

    and what happens when the number of elements increases? This code is O(n2) which doesn't scale at all well. Better is something like:

    my %hits; ++$hits{$_} for @a1; my @matched = grep {exists $hits{$_}} @a2;
    True laziness is hard work
Re^2: Array comparison using perl
by ajguitarmaniac (Sexton) on Dec 21, 2010 at 14:54 UTC

    Right on fisher! Thanks!