Re: Removing entry from @rray
- From: Mirco Wahab <wahab-mail@xxxxxx>
- Date: Mon, 11 Dec 2006 12:50:27 +0100
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.
.
- References:
- Removing entry from @rray
- From: Robert Valcourt
- Removing entry from @rray
- Prev by Date: Re: Array as instance variable
- Next by Date: Re: regex /[^A-Z]{3,}/)
- Previous by thread: Re: Removing entry from @rray
- Next by thread: Re: Removing entry from @rray
- Index(es):
Relevant Pages
|