neversaint has asked for the wisdom of the Perl Monks concerning the following question:

Dear Masters,
I have to arrays. One is larger than the other, and the smaller one is the subset.
Now what I want to do is to remove the elements in the larger array based on that smaller one.
Something like:
perl -MData::Dumper -e ' @ar1 = qw( a b c d e ); @sl = qw( b d ); @ar2 = @ar1[@sl]; print Dumper \@ar2;'
Now from that code I expect it to return
$VAR1 = [ 'a', 'c', 'e' ];
But it doesn't. What's wrong with it? And is there a quicker/better way to do it?

---
neversaint and everlastingly indebted.......

Replies are listed 'Best First'.
Re: Finding the Remaining of Array by Slice - A quick way?
by Zaxo (Archbishop) on Aug 29, 2005 at 09:21 UTC

    my %sl; @sl{@sl} = (); my @ar2 = grep {!exists $sl{$_}} @ar1; print Dumper \@ar2;

    After Compline,
    Zaxo

Re: Finding the Remaining of Array by Slice - A quick way?
by davidrw (Prior) on Aug 29, 2005 at 11:47 UTC
    The above hash/grep solutions and the link to the Q&A node How can I find the union/difference/intersection of two arrays? are both good, so i won't repeat the solution, but i will answer the other part about why your solution didn't work ..

    @ar2 = @ar1[@sl];
    Is an array slice setting elements of @ar2 to elements of @ar1 using the values of @s1 as indices. To write it out longhand, it is doing:
    $ar2[0] = $ar1[ $s1[0] ]; $ar2[1] = $ar1[ $s1[1] ];
    Now substitute in the values of @s1 elements:
    $ar2[0] = $ar1[ 'b' ]; $ar2[1] = $ar1[ 'd' ];
    And we see why it failed -- the characters 'b' and 'd' cannot be used as the index of an array. Apparently from the output, perl was cast the chars to 0 and that's why both elements are 'a'.

    The last lesson here is always use strict and warnings by default .. Adding use warnings (or perl -w) generates these messages:
    Argument "b" isn't numeric in array slice at /tmp/r line 10. Argument "d" isn't numeric in array slice at /tmp/r line 10.
Re: Finding the Remaining of Array by Slice - A quick way?
by Fang (Pilgrim) on Aug 29, 2005 at 09:25 UTC

    Unless you absolutely need to use a slice, this node offers other viable solutions.

Re: Finding the Remaining of Array by Slice - A quick way?
by kprasanna_79 (Hermit) on Aug 29, 2005 at 10:56 UTC
    my @list = qw/1 2 3/; %temp=(); my @stoplist = qw/1 2/; @temp{@list} = (); delete @temp{@stoplist}; print keys %temp;
    -prasanna.k