in reply to Deleting specific element in array in FOREACH loop
If you want to delete from the array you need to watch out for the trap that arrises when you delete an element and shift the remaining elements down one place. One way around it is to build a list of elements for deletion:
#!/usr/bin/perl -w use strict; use Data::Dumper; my @array = qw( 1 2 3 4 5 6 7 ); my @delList; foreach my $index (0 .. $#array) { # Delete element here if it matches. push @delList, $index if ($array[$index] & 1) == 0; # Add for deleti +on } splice @array, $_, 1 for reverse @delList; print Dumper \@array;
The down side is that you don't have an alias to the element, you have its index. Another way to do it is to push the elements you want to keep to another array:
... my @keep; foreach my $element (@array) { # Add element here if it doesn't match. push @keep, $element if ($element & 1) != 0; # Add for deletion } ...
|
|---|