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

Hi. I'm having an ambiguity problem with the {} brackets in perl regex. It thinks I'm trying to reference a nonexistent hash when really I just have variables for the desired match and the number of times I want to match.

my code:

$string = hithereHelloHellohithere $match = Hello; $repeat = 2; $string =~ m/$match{$repeat}/;
Gives me errors indicating it's looking for a hash that doesn't exist.

Replies are listed 'Best First'.
Re: Regex curly bracket ambiguity
by ysth (Canon) on Jun 21, 2007 at 16:03 UTC
    To indicate where a variable ends in a regex, you surround the variable with {}: $string =~ m/${match}{$repeat}/;.

    That keeps it from thinking you mean %match, but gives you m/Hello{2}/ (match "Hell", followed by two "o"s). To make the repeat apply to the whole $match, you need to group it: m/(?:${match}){$repeat}/, which makes the added {} unnecessary, leaving you with m/(?:$match){$repeat}/.

      Thank you that was incredibly helpful.
      
      so now that I have regular brackets around (?:$match); what 
      do I do if I want to capture the whole thing?
      
      eg with:
      m/((?:$match){$repeat})/
      
      will $1 give me everything or just $match back?
      
      
        $1 will give you the whole match. (?:) is a non-capturing grouping, so it does not affect $1, etc. If you used regular parens around $match, it would be returned in $2.

        Caution: Contents may have been coded under pressure.
Re: Regex curly bracket ambiguity
by halley (Prior) on Jun 21, 2007 at 15:05 UTC
    It's pretty easy to find some other syntax that will not change the meaning of your pattern, but give Perl more clues as to your intent. For example, a (?:...) non-capturing group.
    $string =~ m/(?:$match){$repeat}/;

    --
    [ e d @ h a l l e y . c c ]

Re: Regex curly bracket ambiguity
by naikonta (Curate) on Jun 21, 2007 at 18:36 UTC
    This was just discussed recently from another point of view.

    Open source softwares? Share and enjoy. Make profit from them if you can. Yet, share and enjoy!