Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Deleting specific array elements

by salva (Canon)
on Nov 26, 2008 at 09:47 UTC ( [id://726050]=note: print w/replies, xml ) Need Help??


in reply to Deleting specific array elements

Probably, the easiest way is to use grep:
@molecules = grep { $_ ne "\n" } @molecules;

Replies are listed 'Best First'.
Re^2: Deleting specific array elements
by Crian (Curate) on Nov 26, 2008 at 10:00 UTC

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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (4)
As of 2024-04-19 13:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found