t-rex has asked for the wisdom of the Perl Monks concerning the following question:

I have two arrays

A1=0 1 2 3 4 5 6 7 A2=6 7

I have to remove elements 6 and 7 from A1 which are present in A2. Basically whatever elements are present in A2 should be removed from A1. How do i do it, one way was splice but i am getting different outputs not what I expect ?

Note : A1 is for me is an array of reference

foreach my $A1 (@cpu_lists) @A2 = @{$A1}[-n..-1]; #A2 is derived from A1 @{$A1} = splice @{$A1},6,-1;#A1 should be spliced to remove elements o +f A2 where n = number of elements which we want in A2.

Replies are listed 'Best First'.
Re: removing elements in array in Perl
by Athanasius (Archbishop) on Nov 23, 2016 at 09:21 UTC

    Hello t-rex,

    What you describe is a set difference. For example, using Set::Scalar:

    use strict; use warnings; use Set::Scalar; my $a1 = Set::Scalar->new(qw(0 1 2 3 4 5 6 7)); my $a2 = Set::Scalar->new(qw(6 7)); my $diff = $a1->difference($a2); print $diff;

    Output:

    19:16 >perl 1718_SoPW.pl (0 1 2 3 4 5) 19:16 >

    However, you note that your first array is an array of references. So, when you exclude elements from A1 because they also appear in A2, do you want to match the references themselves, or the things they refer to? You will need to be clear on this point before the monks can help you further.

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Re: removing elements in array in perl
by Corion (Patriarch) on Nov 23, 2016 at 09:05 UTC

      updated the question with my code, pls check it now

        Ah - I was confused about your double usage of numbers as array elements and array indices.

        To me, it feels as if you have a number $n and want to remove $n elements from @A1 and put them into A2:

        use strict; use Data::Dumper; my @A1 = qw(a b c d e f g); my $n = 2; my @A2 = splice @A1, @A1-$n, $n; print Dumper [\@A1, \@A2]; __END__ $VAR1 = [ [ 'a', 'b', 'c', 'd', 'e' ], [ 'f', 'g' ] ];
Re: removing elements in array in perl
by Marshall (Canon) on Nov 23, 2016 at 17:12 UTC
    If you wanted to remove any element in A2 from A1, which might appear in any order. I would convert @A2 to a hash and use grep.
    #!/usr/bin/perl use strict; use warnings; my @A1= qw/0 1 6 2 3 7 4 5/; my @A2= qw/6 7/; my %hash = map {$_ => 1}@A2; @A1 = grep {!defined $hash{$_}}@A1; print "@A1\n"; #prints: 0 1 2 3 4 5