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

Hi Monks,

Why wouldnt this work

($last_41) = $buffer =~ /(.*{41})$/;
I need to get only the last 41 chars of the var $buffer into $last_41

Edited by Arunbear: Changed title from 'Why doesnt this work', as per Monastery guidelines

Replies are listed 'Best First'.
Re: Regex to match last n characters of a string
by BrowserUk (Patriarch) on May 13, 2005 at 06:18 UTC

    If you enable warnings you'll see

    Nested quantifiers in regex; marked by <-- HERE in m/(.*{ <-- HERE 41} +)$/ a

    Which tells you that your regex should be

    /(.{41})$/

    Note the absence of '*'.

    Alternatively, you could also use

    $last_41 = substr $buffer, -41;

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
    "Science is about questioning the status quo. Questioning authority".
    The "good enough" maybe good enough for the now, and perfection maybe unobtainable, but that should not preclude us from striving for perfection, when time, circumstance or desire allow.
Re: Regex to match last n characters of a string
by Zaxo (Archbishop) on May 13, 2005 at 06:21 UTC

    You have an error in the regex; too many quantifiers - drop the asterisk, ($last_41) = $buffer =~ /(.{41})$/; You could also do this with substr, $last_41 = substr $buffer, -41;

    After Compline,
    Zaxo

Re: Regex to match last n characters of a string
by gopalr (Priest) on May 13, 2005 at 06:25 UTC

    Remove the asteric(*) and run it.

Re: Regex to match last n characters of a string
by displeaser (Hermit) on May 13, 2005 at 06:34 UTC
    Hi,
    after using diagnositics I get the following:

    (F) You can't quantify a quantifier without intervening parentheses. So things like ** or +* or ?* are illegal. The <-- HERE shows in the regular expression about where the problem was discovered. This should work:

    use strict;
    use warnings;
    use diagnostics;
    my $last_41;
    my $buffer="a"x50;
    ($last_41)= $buffer =~ /(.*){41}$/;


    Hope this helps some
Re: Regex to match last n characters of a string
by displeaser (Hermit) on May 13, 2005 at 07:06 UTC
    oops,sorry about that

    I should have looked at this a little better,

    use strict;
    use warnings;
    use diagnostics;
    my $buffer="a"x50;
    $buffer =~ /(.{41})$/;
    print $1;


    now this actually works.
    The perl "Perlre" doc has the answer (in a better way then i can phrase it. I think that the curly bracket was been interpretted as a normal character and not a quantifier.
    again sorry for original post.