get last characters out of string?
Anonymous Monk
created: 2006-05-03 19:18:10
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?
Re: get last characters out of string?
created: 2006-05-03 19:20:35
[Anonymous Monk],
Why not use [doc://substr] - that's what it is for.
my $last_60 = substr($str, -60);

Cheers - [Limbic~Region|L~R]

Re: get last characters out of string?
created: 2006-05-03 19:21:15

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?
created: 2006-05-03 19:23:46

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.

Re^2: get last characters out of string?
created: 2006-05-03 19:48:47

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.

Re: get last characters out of string?
created: 2006-05-04 01:14:36

Another possibility. ...this one caters to the irrational fear of [doc://substr]:

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

Dave

perlmonks.org content © perlmonks.org and Anonymous Monk, davido, Fletch, GrandFather, ikegami, Limbic~Region

prlmnks.org © 2006 edmund von der burg (eccles & toad)

v 0.03