substr - get or alter a portion of a string
SYNOPSIS:
=========
substr EXPR,OFFSET,LEN,REPLACEMENT
substr EXPR,OFFSET,LEN
substr EXPR,OFFSET
DESCRIPTION:
============
Extracts a substring out of EXPR and returns it. First
character is at offset 0, or whatever you've set $[ to
(but don't do that). If OFFSET is negative (or more
precisely, less than $[ ), starts that far from the end of
the string. If LEN is omitted, returns everything to the
end of the string. If LEN is negative, leaves that many
characters off the end of the string.
So, your -1 where the OFFSET is at, is starting from the end of the string. And since you are giving the length, you are getting only the last character of your string.
UPDATE: You might also want to read this
TStanley
--------
Never underestimate the power of very stupid people in large groups -- Anonymous | [reply] |
The problem is that even using a negative starting position, substr() is still looking to start there and grab $length characters to the right. Since you are starting at the last character, there is nothing else to grab.
What you want to do is start $length characters in from the right, and grab everything else, like:
substr($filename,-$length);
More docs on substr() can be found
here.
- Matt Riffle | [reply] [d/l] |
I think substr is doing exactly what you're asking it to.
You've set the offset to -1. That means, "Start at the last character on the string." From the last character of the string to the last character + $length characters is still only going to return the last character.
What had you hoped to get instead?
_______________
D
a
m
n
D
i
r
t
y
A
p
e
Home Node
|
Email
| [reply] [d/l] [select] |
I was hoping to get a certain number($length) of characters from the end of the string. But using -$lenght returns "" regardless of $length.
| [reply] |
my $offset = -5; # or however many characters from the end
# that you want
my $new_string = substr $filename, $offset;
UPDATE: You might also want to read this
TStanley
--------
Never underestimate the power of very stupid people in large groups -- Anonymous | [reply] [d/l] |
Just a matter of subtraction then to go back a
specified number of characters from the end of a string.
#!perl -w
use strict;
my $str = "me like cookies";
my $slen = length($str);
my $howfarback = 7;
#Pick from $howfarback position back for substring
my $newstr=substr($str, $slen - $howfarback, $howfarback);
print "$newstr \n";
nandeya | [reply] [d/l] |