Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Re^2: Deleting specific array elements

by Crian (Chaplain)
on Nov 26, 2008 at 10:00 UTC ( #726054=note: print w/replies, xml ) Need Help??

in reply to Re: Deleting specific array elements
in thread Deleting specific array elements

If your array is too big to copy it, try something like this:

for my $m (reverse 0 .. $#molecules) { if ($molecules[$m] eq "\n"){ splice (@molecules, $m, 1); } }

Replies are listed 'Best First'.
Re^3: Deleting specific array elements
by salva (Abbot) on Nov 26, 2008 at 10:47 UTC
    That's very inefficient, O(N^2) worst case under the hood. If your data is so big it doesn't fits in memory, it is not a good solution either. Note also, that the grep solution is swap-friendly as it access memory in a sequential manner.

    Anyway, if you want to minimize memory usage and still be O(N):

    my $to = 0; for (@m) { $m[$to++] = $_ if $_ ne "\n"; } splice @m, $to;
Re^3: Deleting specific array elements
by JavaFan (Canon) on Nov 26, 2008 at 10:47 UTC
    Unfortunally, if the array is large, and there's a significant number of elements "\n" in the array, the repeated splicing can be slow. splice() is an O(n) operation (with n the length of the array), and that's a tight worst case bound (splice may require shifting half the array). If you have a large array, and cannot afford to copy, you can still remove the offending elements in situ:
    my $j = 0; for (my $i = 0; $i < @molecules; $i ++) { $molecules[$j++] = $molecules[$i] unless $molecules[$i] eq "\n"; } splice @molecules, $j;
      for (my $i = 0; $i < @molecules; $i ++) {

      Should n't that be as

      for (my $i = 0; $i < scalar(@molecules); $i ++) {
        Why? < provides scalar context to its operands.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://726054]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (6)
As of 2018-06-24 07:24 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (126 votes). Check out past polls.