Manipulating a Substring with substr
The substr operator works with only a part of a larger string. It looks like
this:
$part = substr($string, $initial_position, $length);
It takes three arguments: a string value, a zero-based initial
position (like the return value of index), and a length for the substring. The
return value is the substring:
my $mineral = substr("Fred J. Flintstone", 8, 5); # gets "Flint"
my $rock = substr "Fred J. Flintstone", 13, 1000; # gets "stone"As you may have noticed in the previous example, if the requested
length (1000 characters, in this
case) would go past the end of the string, there’s no complaint from
Perl, but you simply get a shorter string than you might have. But if
you want to be sure to go to the end of the string, however long or
short it may be, just omit that third parameter (the length), like
this:
my $pebble = substr "Fred J. Flintstone", 13; # gets "stone"
The initial position of the substring in the larger string can be
negative, counting from the end of the string (that is, position
−1 is the last character).[*] In this example, position -3 is three characters from the end of the
string, which is the location of the letter i:
my $out = substr("some very long string", −3, 2); # $out gets "in"As you might expect, index and
substr work well together. In this
example, we can extract a substring that starts at the location of the
letter l:
my $long = "some very very long string"; my $right = substr($long, index($long, "l") );
Now here’s something ...