[Chicago-talk] Array diff

Steven Lembark lembark at wrkhors.com
Wed Aug 6 14:27:12 PDT 2008


> Need to diff() 2 arrays, anyone used Array::Diff? Docs say it returns
> added and delted arrays but the example given shows a scalar.
> 
>     my @old = ( 'a', 'b', 'c' );
>     my @new = ( 'b', 'c', 'd' );
>     
>     my $diff = Array::Diff->diff( \@old, \@new );
>     
>     $diff->count   # 2
>     $diff->added   # [ 'd' ];
>     $diff->deleted # [ 'a' ];
> 
> So, would the added be @added = $diff::added? Am I missing something
> obvious?
> 
> In my usage here, @old has 480 elements, @new has 489.

Returns an arrayref:

       DB<1> @a = ( 1 .. 10 )

       DB<2> @b = ( 2 .. 11 )

       DB<3> x $c = Array::Diff->diff( \@a, \@b )
       0  Array::Diff=HASH(0xd97cc0)
          'added' => ARRAY(0xd97ca0)
             0  11
          'count' => 2
          'deleted' => ARRAY(0xd51910)
             0  1

       DB<4> x $c->added
       0  ARRAY(0xd97ca0)
          0  11

Large-ish arrays or differences could turn this
into something of a memory hog.

Hash slice with delete would give you a quick
list of the excess in one list over the other
if that's all you need:

       sub added
       {
             my ( $a, $b ) = @_;

             my %tmp     = ();

             @tmp{ @$b } = ();

             delete @tmp{ @$a };

             wantarray ? keys %tmp : [ keys %tmp ]
       }


More information about the Chicago-talk mailing list