Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

Looping through array with foreach

dbrandtdbrandt Posts: 43Member
Here's what I want to do.

foreach (@array)
if #condition is true
delete #current array element in loop

So how do I get the current element in the loop? "Delete $_" doesn't work...


  • SouldrinkerSouldrinker Posts: 143Member
    : Here's what I want to do.
    foreach (@array)
    my $var = $_;
    if #condition is true
    delete $var;
    : So how do I get the current element in the loop? "Delete $_"
    : doesn't work...

    as far as I know, you have to read out $_ in the first line of your loop
    best regards,

    sebastian besteman
  • JonathanJonathan Posts: 2,914Member
    The problem is that delete on an array requires an index, not the value of the element itself. So you need to do a normal for loop...

    [code]for (0..$#array) {
    if (condition involving $array[$_]) {
    delete $array[$_];

    However, a far more elegant way to do this is use grep.

    [code]@array = grep { !condition } @array;[/code]

    I write !condition because what goes in the block is the condition that has to be true to keep the value, so you need to invert your condition.

    (tr/yuiqwert/her anot/))for($::b);for($::c){$_.=$^X;
    /(p.{2}l)/;$_=$1}$::b=~/(..)$/;print("$::a$::b $::c hack$1.");
Sign In or Register to comment.