Re: Removing entry from @rray



Robert Valcourt wrote:
My program reads the contents of a text file, and places each line into the array. Here are my two methods:

Using Splicing
=========================
...
Redefining the @array element inside to loop
=========================



Aside from Anno's and John's comments,
I'd like to make another remark.

Both of your variants won't work,
becvause you can't simply 'eq' a
variable against a string read from
a file (which may at least contain a
'\n' and probably a lot more)

Suppose we have a simple "address file":

Smarf Boomtown Boomstreet 23
Smith Huntington Hunstreet 12
Solch Berlin Berlstrasse 123

Then you could read all except "Smith ..."
(as the other posts suggested => grep) by
"grep negated regex":

...
my $variable = 'Smith';
open (my $addresses, '<', 'addressbook.txt') or die "without remorse: $!";
my @entries = grep !/\b$variable\b/, <$addresses>;
...

(\bWORD\b) means: WORD must be delimited by word boundaries,
so "Smithnwesson" woudn't match.

I would also like to ask about terminating a loop ... obviously after a match is found I would want to terminate the loop so that it doesn't waste time checking all the other array elements for a match. Suprisingly I was not able to source this answer. I once read somewhere that a command called "return" or something is used, thoughts?

That's called 'last':

...
...
for my $index (0..@entries-1) {
if( $entries[$index] =~ /\b$variable\b/ ) {
splice @entries, $index, 1;
last;
}
}
...


Regards

M.
.



Relevant Pages

  • Re: Common Lisp implementations are still multiple times slower than C
    ... ARRAY element type when doing MAKE-ARRAY. ... that a simple-vector can hold every element. ... used "(loop for y fixnum from 0 below height..." ...
    (comp.lang.lisp)
  • Re: Efficient solution needed
    ... > Can any one plzz solve the following problem in an efficient way... ... > Multiplies this number by 2. ... A simple loop, ... get a number for which the array element is already 1. ...
    (comp.programming)
  • Re: array question
    ... "RB Smissaert" wrote: ... a differing array element early in the loops so exit early. ... The only refinement I can think of is loop in such a way that you are ...
    (microsoft.public.excel.programming)
  • Re: how to search d15?
    ... of each array element? ... but I'm too busy to write a test example right now. ... concatenating the results into the label text in a loop. ... But not getting "d15" AT ALL? ...
    (microsoft.public.vb.general.discussion)