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

Hi All, Please see my code below
if ($cache_ref->{Index}[$i]=~/\Q($fromto_digest)/ or ref->{Index}[$i]= +~/\Q($tofrom_digest)/) { $cache_index=$1; $index_match=1; last; }
The variables $fromtodigest and $tofromdigest are both SHA1 digests. It is necessary to include the \Q condition as without it I get an error stating "Unmatched bracket..." where a bracket is one of the symbols in the digest. The idea of this if statement is that if there is a match then the match should be returned. However with the return match brackets in the if statement, even with a known match the program does not enter into the if statement. Without the brackets the program will enter the if statement. But I need the match to be returned!!! Can anyone see what the problem is??

Replies are listed 'Best First'.
Re: Returning a match
by pfaut (Priest) on Mar 11, 2003 at 16:00 UTC

    It sounds strange that you are using a digest as a regex. Are you sure you don't really want to test for equality?

    if ($cache_ref->{Index}[$i] eq $fromto_digest || ref->{Index}[$i] eq $ +tofrom_digest) { $cache_index=$1; $index_match=1; last; }
    --- print map { my ($m)=1<<hex($_)&11?' ':''; $m.=substr('AHJPacehklnorstu',hex($_),1) } split //,'2fde0abe76c36c914586c';
Re: Returning a match
by Tomte (Priest) on Mar 11, 2003 at 15:56 UTC

    After a quick glance over the documentation to \Q...\E I'd try

    $cache_ref->{Index}[$i]=~/(\Q$fromto_digest\E)/ or ref->{Index}[$i]=~/ +(\Q$tofrom_digest\E)/)

    because I read the docu as to mean, that in your case the parens and everything will be quoted after the \Q

    I'm tired, so don't count on me ;-)

    regards,
    tomte


    Edit: ++pfaut, I knew there was something 'fishy' but couldn't get it

Re: Returning a match
by ihb (Deacon) on Mar 11, 2003 at 15:57 UTC

    Well, you're also quoting the capturing parenthesis, making it just literal parenthesis. That's why the match fails. The solution is to quote only the variables you interpolate. You can either use the quotemeta function, or you can rewrite it to /(\Q$fromto_digest\E)/, where the \E means that the effect of \Q ends.

    Hope I've helped,
    ihb