Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number

Regex problem

by Anonymous Monk
on Feb 16, 2005 at 11:44 UTC ( #431528=perlquestion: print w/replies, xml ) Need Help??
Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks I have a query see the code snippet below
foreach (@index_corr_file) { if ($index == $_) { $is_present_flag = 1; last; } } if ($is_present_flag) { ##do something }
In the above code can i test for the value referred to be $index to be present or not in the array @index_corr_file with in the if condition only. I mean is there a one line answer to the above snippet. Thanks in advance Sid

2005-02-16 Janitored by Arunbear - added code tags, as per Monastery guidelines

Replies are listed 'Best First'.
Re: Regex problem
by edan (Curate) on Feb 16, 2005 at 11:57 UTC
Re: Regex problem
by tphyahoo (Vicar) on Feb 16, 2005 at 11:56 UTC
    In code tags that would be...
    foreach (@index_corr_file) { if ($index == $_) { $is_present_flag = 1; last; } } if ($is_present_flag) { ##do something }
    How is this a regex problem though?
Re: Regex problem
by chb (Deacon) on Feb 16, 2005 at 12:01 UTC
    I think you are looking for grep. See perldoc -f grep.

    Update: not fast enough...
Re: Regex problem
by sh1tn (Priest) on Feb 16, 2005 at 15:16 UTC
    Are you sure you do not miss hashes?
    @index = qw(1 11 23 45 22); $value = 22; #create hash from array map { $index{$_}++ } @index; #testing for existence exists($index{$value}) and print "yes it does"

Re: Regex problem
by Anonymous Monk on Feb 16, 2005 at 12:01 UTC
    Thank your for your early responses, but my concern here is if the array @index_corr_file has something like qw(1 11 23 45 22) and suppose the $index = 2, then the grep function will be true and the if condition will pass. But i want $index to match to only 2 not otherwise. Is there any way to minimize the code. Sid

      If you want to test for equality, then by all means!

      if ( grep { $index == $_ } @index_corr_file ) { # whatever }

      This will help you,

      grep(/^$index$/, @index_corr)


      As edan said, it will help you

      grep{$index==$_} @index_corr


        I downvoted your post, and I'll tell you why - IT'S WRONG! Why would you give somebody a regex solution when they clearly need to test for equality!? What if $index contained regex metacharacters? In short, I think it's a bad habit to use an anchored regex when you mean "equals". perl provides us with == and eq for a reason. Use them.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://431528]
Approved by edan
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (4)
As of 2018-08-14 21:05 GMT
Find Nodes?
    Voting Booth?
    Asked to put a square peg in a round hole, I would:

    Results (155 votes). Check out past polls.