Q: Adding Optional option to expression match

Discussion in 'Perl Misc' started by Martin Daser, May 18, 2006.

  1. Martin Daser

    Martin Daser Guest

    Hello *,
    I am currently writing a small script to search various patterns within
    files.
    Therefore I am looping over a bunch of strings and try to find the
    pattern. Optionally I want to set a variable to certain flags, which can
    be appended to the matching operator. The variable is either empty or
    contains some switches/characters.
    Adding the variable which holds the switches results in a syntax error:

    Scalar found where operator expected at /...../rgrep line 88, near
    "m/($word)/$matchopts"
    syntax error at /...../rgrep line 88, near "m/($word)/$matchopts"
    syntax error at /...../rgrep line 96, near "}"
    Execution of /...../rgrep aborted due to compilation errors.

    Here is the excerpt to give you an idea:

    # set option for ignore case matching; others possible
    $matchopts = "i";
    .....

    # the next line would be line 88
    if ($_ =~ m/($word)/$matchopts)
    {
    .....
    }

    Is there a way to avoid this error? How can I get around it?

    Any help is appreciated! Thanks in advance!

    -- Martin
     
    Martin Daser, May 18, 2006
    #1
    1. Advertisements

  2. m/((?$matchopts)$word)/

    BTW
    Why do you say "don't use $_, use $_ instead"?
     
    Brian McCauley, May 18, 2006
    #2
    1. Advertisements

  3. Martin Daser

    Martin Daser Guest

    Thanks! that did the job!

     
    Martin Daser, May 18, 2006
    #3
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.