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

How do monks get Perl regular expressions to only look forward if the previous regular expression sub component has been matched?

Title edit by tye

Replies are listed 'Best First'.
Re: regexp
by BrowserUk (Patriarch) on Jun 13, 2003 at 12:57 UTC

    Make the conditional part conditional:). Eg.

    $str =~ m[ (\d{1,4}) (?: \t (.{1,40}) )? # << $2 is condtional. ]x;

    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "When I'm working on a problem, I never think about beauty. I think only how to solve the problem. But when I have finished, if the solution is not beautiful, I know it is wrong." -Richard Buckminster Fuller


Re: regexp
by matth (Monk) on Jun 13, 2003 at 12:35 UTC
    For example:.......... (\d{1,4})\t(.{1,40}) ............I only want to look at $1 and $2 if the \t is present. If the \t isn't present, I wish to just deal with $1.

      Ah, that would be when you check to see whether $2 is defined or not. You get $2 just because it is written into the source of the expression, not because it matched. Its value will be the value undef if the expression matches and that portion of the expression was not used. So for the expression /(\d{1,4}) (?:\t (.{1,40}) )?/x the tab with following stuff is optional and then you just look at the parts that interest you.