Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

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); } }


Comment on Re^2: Deleting specific array elements
Download Code
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.
Re^3: Deleting specific array elements
by salva (Monsignor) 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;

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://726054]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (9)
As of 2014-11-27 04:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (179 votes), past polls