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 in the previous example, if the requested length (1000 characters, in this case) goes past the end of the string, there’ll be no complaint from Perl, but you get a shorter string than you might have. If you want to be sure to go to the end of the string, however long or short it may be, 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).[298] 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"

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 really cool: The selected portion of the string ...

Get Learning Perl, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.