Connecting Tech Pros Worldwide Forums | Help | Site Map

using grep

Newbie
 
Join Date: Aug 2007
Posts: 13
#1: Oct 17 '07
Hi I want to is this right if I want to search an array and evaluate as true for IF statement...
Expand|Select|Wrap|Line Numbers
  1. if(grep{ $_ == $p }@p1)
  2. {
  3.  
  4. }
Any Suggestions...

eWish's Avatar
Moderator
 
Join Date: Jul 2007
Location: Arkansas
Posts: 900
#2: Oct 17 '07

re: using grep


They way you are trying I don't believe will return anything.
Expand|Select|Wrap|Line Numbers
  1. my @p1 = (qw{22 33 43 56 77 34});
  2. my @p2;
  3. my $n = 34;
  4.  
  5. if (@p2 = grep {/^$n$/} @p1) {
  6.     print @p2,"\n";
  7. } else {
  8.     print "No Match's were found\n";
  9. }
KevinADC's Avatar
Expert
 
Join Date: Jan 2007
Location: Southern California USA
Posts: 4,091
#3: Oct 17 '07

re: using grep


Quote:

Originally Posted by eWish

They way you are trying I don't believe will return anything.

It will return 1 (true) or 0 (false). But it is not very efficient because it has to check every element of the array. A for/foreach loop should be more efficient and could be way more efficient in some circumstances. For example:

Expand|Select|Wrap|Line Numbers
  1. @array = 0..1000000000;
  2. $p = 0;
  3.  
  4. for (@array) {
  5.    if ($_ == $p) {
  6.       print "true";
  7.       last;
  8.    }
that will be much faster than:

Expand|Select|Wrap|Line Numbers
  1. if (grep {$_ == $p} @array) {
  2.    print "true";
  3. }
Newbie
 
Join Date: Aug 2007
Posts: 13
#4: Oct 17 '07

re: using grep


Quote:

Originally Posted by KevinADC

It will return 1 (true) or 0 (false). But it is not very efficient because it has to check every element of the array. A for/foreach loop should be more efficient and could be way more efficient in some circumstances. For example:

Expand|Select|Wrap|Line Numbers
  1. @array = 0..1000000000;
  2. $p = 0;
  3.  
  4. for (@array) {
  5.    if ($_ == $p) {
  6.       print "true";
  7.       last;
  8.    }
that will be much faster than:

Expand|Select|Wrap|Line Numbers
  1. if (grep {$_ == $p} @array) {
  2.    print "true";
  3. }


thanks for the suggestion...I asked for that as it was not working for me with the code I mentioned....
Anyway I will be using the for loop....
KevinADC's Avatar
Expert
 
Join Date: Jan 2007
Location: Southern California USA
Posts: 4,091
#5: Oct 17 '07

re: using grep


It will work:

Expand|Select|Wrap|Line Numbers
  1. @p1 = 1..5;
  2. $p = 3;
  3. if (grep{ $_ == $p } @p1) {
  4.    print "true";
  5. }
  6. else {
  7.    print "false";
  8. }    
Reply