swissknife has asked for the wisdom of the Perl Monks concerning the following question:

Hello

i am trying to match exact match using grep function. I have few values in an array which looks like below

print "@arr2"; output: mcs scr tsz unh print "@arr1"; output: spec.srn.1235 spec.mcs.1235

now i am following below operation but it always go to ELSE condition where i would expect for value "spec.mcs.1235" to come in IF condition

foreach $strfile (@arr1) { @arr3 = split(/[.\n]/, $strfile); if (grep (/^@arr3[1]$/, @arr2)) { print "Entered in IF"; } else { print "Entered in ELSE"; } }
Could someone let me know what is wrong here? swissknife

Replies are listed 'Best First'.
Re: perl grep with regex
by choroba (Cardinal) on Jun 30, 2014 at 12:36 UTC
    It works for me:

    Are you sure your input contains what you think? Try adding the information to the output:

    if (grep (/^$arr3[1]$/, @arr2)) { print "Entered in IF Loop: /^$arr3[1]\$/ found in (@arr2)\n"; } else { print "Entered in ELSE Loop: /^$arr3[1]\$/ not found in (@arr2 +)\n"; }

    Also note that I used $arr3[1] instead of @arr3[1]. warnings told me to do so.

    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

      Thank you for your response. Does it make any difference when i read arr2 from a file? (in my actual code i get this array by reading a file). i tried as you suggested and got below output.

      Entered in else loop: /^mcs$/ found in (scr mcs tsz unh )
        There's probably some whitespace at the end of the lines in the file. Remove it:
        s/\s+$// for @arr2;
        لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: perl grep with regex
by LanX (Saint) on Jun 30, 2014 at 12:37 UTC

    @arr3[1] looks very wrong, try $arr3[1]

    Why don't you use warnings ?

    Cheers Rolf

    (addicted to the Perl Programming Language)

OT: if loop (was Re: perl grep with regex)
by roboticus (Chancellor) on Jun 30, 2014 at 12:55 UTC

    swissknife:

    I have a question: Where did you find the term "if loop"? I've seen it here on perlmonks a few times as of late, and I'm wondering if there's a common source of (mis)information that causes people to think if statements are looping constructs.

    ...roboticus

    When your only tool is a hammer, all problems look like your thumb.

      It was completely mistake at my end. Doing lot of things together can make one to make such mistake.

        You really should consider keeping your code properly formatted for maximum readability. Tools like PerlTidy can help you:

        foreach $strfile (@arr1) { @arr3 = split(/[.\n]/, $strfile); if (grep (/^@arr3[1]$/, @arr2)) { print "Entered in IF"; } else { print "Entered in ELSE"; } }

        jeffa

        L-LL-L--L-LL-L--L-LL-L--
        -R--R-RR-R--R-RR-R--R-RR
        B--B--B--B--B--B--B--B--
        H---H---H---H---H---H---
        (the triplet paradiddle with high-hat)