Simple way to kill @array element?

R

Robert TV

Hi, I'm wondering if there is a simple way to kill (remove) an element from
an array when inside a foreach loop. I can easily add an element to an array
like below:

push(@list, $element);

But when it comes to removing an element, it seems (as far as my research
shows) one would normally use the splice command. This means starting a
counter, when the condition is met, reduce counter by one, then splice it
.... I am looking for something a little more simple like this ("unpush"
syntax not real)

$element = "Mike";

foreach $list (@list) {
if ($list eq $element) {
unpush (this specific @array element)
}
}

Am I dreaming? TIA!

Robert
 
G

Gunnar Hjalmarsson

Robert said:
Hi, I'm wondering if there is a simple way to kill (remove) an
element from an array when inside a foreach loop. I can easily add
an element to an array like below:

push(@list, $element);

But when it comes to removing an element, it seems (as far as my
research shows) one would normally use the splice command. This
means starting a counter, when the condition is met, reduce counter
by one, then splice it

This is a for loop without a separate counter:

for (0..$#list) {
if ($list[$_] eq $element) {
splice @list, $_, 1;
last;
}
}

But it can be written much simpler using the grep() function:

@list = grep { $_ ne $element } @list;
 
B

Ben Morrow

Robert TV said:
Hi, I'm wondering if there is a simple way to kill (remove) an element from
an array when inside a foreach loop. I can easily add an element to an array
like below:

push(@list, $element);

But when it comes to removing an element, it seems (as far as my research
shows) one would normally use the splice command. This means starting a
counter, when the condition is met, reduce counter by one, then splice it
... I am looking for something a little more simple like this ("unpush"
syntax not real)

From the Book of perlsyn, Chapter 7, Verse vi:

| If any part of LIST is an array, "foreach" will get very confused if
| you add or remove elements within the loop body, for example with
| "splice". So don't do that.

HTH

Ben
 
T

Txema Glez Izarzugaza

I am not very sure that i am undertstanding properly your problem, but i
think that the command "pop" is the opposite (more or less) of "push". Maybe
is what you are looking for.

Good Luck,
Txema
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,141
Messages
2,570,817
Members
47,367
Latest member
mahdiharooniir

Latest Threads

Top