Date: Mon, 16 Jul 2001 17:27:38 +0100 From: Jasper McCrea To: Wali Haidri Subject: Re: ARRAYS: find common values Message-Id: <3B5315FA.44B1AC12@guideguide.com> Wali Haidri wrote: > > I want to out put the common values in the two arrays below. Following > code does work but it is very slow. I hope somebody can suggest a > better way. isn't this an FAQ. ie use a hash. # haven't tested this, and am assuming (probably correctly :) ) # that uc works on $_ my %users2 = map { uc => 1 } @users2; foreach my $user (sort { $a cmp $b} map { uc } @users) { push @finalusers, $user if $users2{$user}; } return @finalusers; probably you'll find that this isn't much faster. But it isn't what perl was designed to do, I guess. I also not that you're using next LINE when the code doesn't do anything afterward, anyway. There's only a necessity to put a next in if there's more code you want to avoid. I have also uc'd all values straight away. You waste time by testing against a uced $val1 (this ucing being done every time), and then if you actually want to use it, you uc it anyway. You're also declaring variables that only need a small scope with a much larger scope ($val1, $val2). Jasper > > sub get_usersByToken3{ > > # my (@users) defined somewhere else and has a list of users. > # my (users2) " " " " " > my (@finalusers); > my ($tval, $val1, $val2); > > # FIRST SORT BOTH ARRAYS > > @users = sort { uc($a) cmp uc($b) } @users; > @users2 = sort { uc($a) cmp uc($b) } @users2; > > # NOW FOR EACH ELEMENT IN LIST 1, TRY TO FIND IT IN LIST 2. IF FOUND > # PUSH IT TO AN OUTPUT ARRAY AND EXIT OUT OF THIS LOOK BACK TO THE FIRST > # foreach LOOP. > > LINE: > foreach $val1 (@users){ > foreach $val2 (@users2){ > if ( $val2 eq uc($val1) ) { > push(@finalusers, uc($val1)); > next LINE; > } > } > } # end of foreach > return (@finalusers); > } > > Please cc to my email address if possible. Thanks. > > Wali Haidri > whaidri@ford.com -- split//,'019617511192'. '17011111610114101114'. '21011141011840799901'. '17101174'; foreach(0.. $#_){$_[$_ ++]^=$_[$_ --]^=$_[$_ ]^=$_[++ $_]if!($_% 2)}$g.=$_ ,chr($g)=~ /(\w)/&&($o.=$1and $g='')foreach@_; print"$o\n"