Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Hi, Say I have an array @a_array

Status
Not open for further replies.

milage

Programmer
Jul 13, 2001
58
US
Hi,

Say I have an array @a_array which contain objects which are in turn arrays with 6 elements. I am trying to delete objects from that array whose first element equals an element of another array.

So far I have got this far (assume that @a_array and @ignore_variables has been declared and populated earlier).

my $i;
my $j;
for $i (0 .. $#a_array) {
$j=0;
for $j (0 .. $#ignore_variables){

if ($ignore_variables[$j] eq $a_array[$i][0]) {

# Remove it from the array.
delete @a_array[$i];
}
}
}

However, this does not work properly. It removes the values of the object at [$i] but it does not actually remove the object as the array remains the same length and when printed out has a gap where the variable that was deleted was.

What am I doing wrong!

Cheers

Rob
 
It is dangerous to change the size of an array that you are looping over. You would use [tt]splice()[/tt] rather than [tt]delete[/tt] to remove the element of an array, but in this case that won't work properly because you are looping over the array that you are changing. This does screwy things.

You would be better off to create a new array and only copy elements over from @a_array that don't match your ignore list. At the end of the loop you can copy the new array back to @a_array if you wish.

jaa
 
One way to do this:
Code:
@bad = qw( 0 2 4 6 8 10 );

@test = qw( 0 1 2 3 4 5 6 7 8 9 10 );

# hash slice
@bad_hash{@bad} = @bad;

@ok = grep { !exists $bad_hash{$_} } @test;

print "\@ok: @ok\n";

Cheers, Neil :)
 
A slight modification of Neil's idea would work for your multidimentional array, @a_array.
(untested)
Code:
@ok =  grep { !exists $bad_hash{$_->[0]} } @test;
You could even replace @ok with @test and do a direct replacement.

jaa
 
Cheers,

thanks for the suggestions. I went for the copying the ones I wanted to keep into a temporary array and then copying this back onto @a_array approach in the end.

Rob
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top