What is the best way to delete a value from an array in Perl?

前端 未结 14 2372
忘掉有多难
忘掉有多难 2020-12-12 20:17

The array has lots of data and I need to delete two elements.

Below is the code snippet I am using,

my @array = (1,2,3,4,5,5,6,5,4,9);
my $element_o         


        
相关标签:
14条回答
  • 2020-12-12 20:37

    The best I found was a combination of "undef" and "grep":

    foreach $index ( @list_of_indexes_to_be_skiped ) {
          undef($array[$index]);
    }
    @array = grep { defined($_) } @array;
    

    That does the trick! Federico

    0 讨论(0)
  • 2020-12-12 20:38

    Delete all occurrences of 'something' if array.

    Based on SquareCog answer's:

    my @arr = ('1','2','3','4','3','2', '3','4','3');
    my @dix = grep { $arr[$_] eq '4' } 0..$#arr;
    my $o = 0;
    for (@dix) {
        splice(@arr, $_-$o, 1);
        $o++;
    }
    print join("\n", @arr);
    

    Each time we remove index from @arr, the next correct index to delete will be $_-current_loop_step.

    0 讨论(0)
  • 2020-12-12 20:39

    splice will remove array element(s) by index. Use grep, as in your example, to search and remove.

    0 讨论(0)
  • 2020-12-12 20:44

    if you change

    my @del_indexes = grep { $arr[$_] eq 'foo' } 0..$#arr;
    

    to

    my @del_indexes = reverse(grep { $arr[$_] eq 'foo' } 0..$#arr);
    

    This avoids the array renumbering issue by removing elements from the back of the array first. Putting a splice() in a foreach loop cleans up @arr. Relatively simple and readable...

    foreach $item (@del_indexes) {
       splice (@arr,$item,1);
    }
    
    0 讨论(0)
  • 2020-12-12 20:47

    Is this something you are going to be doing a lot? If so, you may want to consider a different data structure. Grep is going to search the entire array every time and for a large array could be quite costly. If speed is an issue then you may want to consider using a Hash instead.

    In your example, the key would be the number and the value would be the count of elements of that number.

    0 讨论(0)
  • 2020-12-12 20:51

    I use:

    delete $array[$index];
    

    Perldoc delete.

    0 讨论(0)
提交回复
热议问题