in reply to Creating regex from arrays

Other monks have answered this.

I see only one caveat: if the character "I" can occur in your original array, you will have to escape that. Something like:

$tomatch = join( '|',map {s#|#\\|#s; $_} @results );
And yes, I prefer # over / for regexes to avoid the falling toothpick syndrome.

Liz

Replies are listed 'Best First'.
Re: Re: Creating regex from arrays
by diotalevi (Canon) on Jul 29, 2003 at 16:31 UTC

    The fix to that problem is quotemeta, not selectively escaping pipes

    $tomatch = join "|", map quotemeta, @results;
Re^2: Creating regex from arrays (oops)
by tye (Sage) on Jul 29, 2003 at 17:03 UTC
    map {s#|#\\|#s; $_} @results

    I hope you don't have any other uses for @results as you've modified it in-place.

    Perl doesn't have a great idiom for this. This type of mistake and several others are so common that I really think Perl should have a 'filter' keyword.

    And thanks(++) for bringing up the important point about escaping regular expression metacharacters and prompting diotalevi's reply (which is what I'd use).

                    - tye
      Good point. Apart from using quotemeta, it would have been better to do:
      $tomatch = join '|', map {local $_ = $_; s#\|#\\|#s; $_} @results;
      When actually testing this, I found that my initial solution was flawed in another way: the initial pipe needs to be escaped as well! Does any monk have an idea why that is necessary?

      Liz

        I think you'll slap your forehead for this one. (:

        Does any monk have an idea why [...] the initial pipe needs to be escaped as well

        For the same reason that you realized that you needed to do some escaping in the first place. /|/ matches "either the empty string or the empty string" while /\|/ and /[|]/ match a single vertical bar character.

        So s#|#\\|#g replaces every empty substring of a string with '\|'.

                        - tye