Perl: the Markov chain saw PerlMonks

### Re^2: Deleting specific array elements

by Crian (Deacon)
 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 (Canon) 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.

Create A New User
Domain Nodelet?
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 chanting in the Monastery: (2)
As of 2022-12-03 22:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?

No recent polls found

Notices?