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

Hi, I want to search through a file for the paragraphs marked with <FN1>, <FN2>, <FN3> and so on and push them to a array @fnote. My syntax goes like,

if ($_ =~ /<FN$i++>(.+)\n/){push(@fnote, $1);}

This is inside a while loop which reads through the text file. But when I execute this, I get a error as follows

Nested quantifiers in regex; marked by <--HERE in m/<FN0++ <--HERE>(.+)\n/ at fnote.pl line 16, <F1> line 1.

Could anyone help with the syntax?

Replies are listed 'Best First'.
Re: Searching a sequence of tags using regex
by McDarren (Abbot) on Jul 13, 2006 at 11:34 UTC
    The error refers to your use of $i++ within the pattern match. If you really want to do variable interpolation evaluate code within the pattern match, then you need to enclose it with \Q\E, like so:
    /<FN\Q$i++\E>(.+)\n/
    ...do something like this:
    /<FN(?{$i++})(.+)\n/
    Having said that, I sniff an XY Problem here.
    I'm really not sure what the purpose of that $i++ is.
    Is it some sort of counter, so that you know how many footnotes you have captured?
    If that's the case, you could simply do something like this (untested):
    while (<FILE>) { chomp; #if necessary if ($_ =~ m/<FN\d+>(.+)\n/) { push @fnote, $1; } } my $numfootnotes = scalar @fnote;

    Hope this helps,
    Darren :)

Re: Searching a sequence of tags using regex
by davorg (Chancellor) on Jul 13, 2006 at 11:49 UTC

    You can't use the increment operator in a regex like that. Perl thinks you're trying to use the regex "one or more" match quantifier.

    If you're looking for FN followed by a digit, can't you just do something like:

    /<FN\d+>(.+)\n/

    In fact your whole code can probably be replaced with:

    push @note, /<FN\d+>(.+)\n/g;

    Or (if @note starts off empty):

    @note = /<FN\d+>(.+)\n/g;
    --
    <http://dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: Searching a sequence of tags using regex
by prasadbabu (Prior) on Jul 13, 2006 at 11:33 UTC

    Hi rsriram,

    Here is one way to solve that problem, you are using the increment operator in find pattern of the regex which is not allowed, instead you increment before that and use the variable alone.

    while (<DATA>) { $i++; push(@fnote, $1) if ($_ =~ /<FN$i>(.+)\n/); } $, = "\n"; print @fnote;

    Prasad

A reply falls below the community's threshold of quality. You may see it by logging in.