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

Hello monks! I want to write a piece of code that will grab the last x characters (60 in particular) out of a string. Must I use substrings or is there anything else I should consider?

Replies are listed 'Best First'.
Re: get last characters out of string?
by Limbic~Region (Chancellor) on May 03, 2006 at 23:20 UTC
Re: get last characters out of string?
by GrandFather (Saint) on May 03, 2006 at 23:21 UTC

    substr is the way to go:

    use strict; use warnings; my $str = '1234567890' x 10; print substr $str, -60;

    Prints:

    123456789012345678901234567890123456789012345678901234567890

    DWIM is Perl's answer to Gödel
Re: get last characters out of string?
by davido (Cardinal) on May 04, 2006 at 05:14 UTC

    Another possibility. ...this one caters to the irrational fear of substr:

    my $found; $string =~ m/(.{60})\z/s and $found = $1;

    Dave

Re: get last characters out of string?
by Fletch (Bishop) on May 03, 2006 at 23:23 UTC

    You want to get a substring, but you don't want to use substr? That's almost as inane as the people that periodically show up posting who want to iterate over the contents of an array but not use foreach or map or while.

    I mean you certainly could use substr, but why be explicit when you can obtusely use /(.{1-60})$/ instead.

      Maybe he thought he had to do

      my $start = length($str) - 60; $start = 0 if $start < 0; $substr = substr($str, $start);

      and was looking for a simpler right function? True, he should have read the docs closer, but *understanding* the docs can sometimes be hard.