in reply to Re: Creating regex from arrays
in thread Creating regex from arrays

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

Replies are listed 'Best First'.
Re: Re^2: Creating regex from arrays (oops)
by liz (Monsignor) on Jul 29, 2003 at 18:13 UTC
    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
        *slap*