in reply to Checking if an item exists in an array before adding a record to it.
G'day viffer,
If you declare %params earlier in your code, you can write:
if ($server eq 'lsrch1') { my %params = map { $_ => 1 } @lsrch1; if(! exists($params{$string})) { push (@lsrch1, $string); } }
as:
if ($server eq 'lsrch1') { push @lsrch1, $string unless $params{$string}++; }
You haven't shown the context of your code (which is fine); however, it leaves me in the dark as to advising where exactly to delare %params. Also, I don't know where $string comes from. Here's my test showing how my code might be implemented (adapt for your context as appropriate):
$ perl -Mstrict -Mwarnings -e ' my @strings = qw{a a a b b c d d e e e}; my $server = "lsrch1"; # Fudge for demo my @lsrch1; my %params; for my $string (@strings) { if ($server eq "lsrch1") { push @lsrch1, $string unless $params{$string}++; } } print "\@strings: @strings\n"; print "\%params keys: @{[sort keys %params]}\n"; print "\@lsrch1: @lsrch1\n"; ' @strings: a a a b b c d d e e e %params keys: a b c d e @lsrch1: a b c d e
-- Ken
|
|---|