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

Hi, I'm trying to extract an expression from a line. Here's what I'm doing: my $exp = $line =~ m/[FAR PASCAL|FAR PASCAL_CONV]\ (.*)\(/gi; with $1 I get the expression I want, but also the sring PASCAL ! The $line exp is of the type:
FAR PASCAL what_i_want(etc...)
or
FAR PASCAL_CONV what_i_want(etc...)
What am I doing wrong...? Kind regards, Kepler

Replies are listed 'Best First'.
Re: String extract
by AppleFritter (Vicar) on Jul 22, 2014 at 11:16 UTC

    Your regex is a bit hard to read to say the least, what with the lack of proper code tags, but I think it looks like this:

    my $exp = $line =~ m/[FAR PASCAL|FAR PASCAL_CONV] (.*)/gi;

    Is that right? If so: square brackets indicate a character class, so [FAR PASCAL|FAR PASCAL_CONV] will match any of "|_ ACFLNOPRSV". What you're looking for is either regular parentheses or, if you want to avoid capturing, (?:) (non-capturing parentheses), e.g. like this:

    $line =~ m/(?:FAR PASCAL(?:_CONV)?) (.*)/i;

    If you're only doing a single match, the /g modifier is unnecessary as well; furthermore, the m// operator returns the number of matches in scalar context. If you'd like to store captures for later use, use it in list context:

    $line = "FAR PASCAL_CONV blurb"; my ($expr) = $line =~ m/(?:FAR PASCAL(?:_CONV)?) (.*)/i; # $expr now contains "blurb";

    I hope this helps.