Press "Enter" to skip to content

Perl Substring (substr)

Substring (substr)

The substring function is a way to get a portion of a string value, rather than using the entire value. The value can then be used in a loop or a conditional statement, or just for its own purposes. For this one, you will probably want the general form of the function first. The function is usually set to a variable so that the variable contains the value of the substring:

$portion = substr($string_variable, start number, length);

Your $string_variable will be the variable from which you wish to create the substring. The start number is the character within the string from which you want to start your substring. Remember, though- the first number in a string here is zero rather than 1, so be careful when you make the count. The length above is the amount of characters you wish to take out of the string.

So, if we had a variable named $toy with a value of “baseball”, but we wanted to get the last four characters rather than the full string, we would write something like this:

[code]
$toy=”baseball”;
$value = substr($, 4, 9);
print “All small boys love to play $toy.”;
print “What would they play without a $value?”;
[/code]

Yes, the substring turns out to be “ball”. It starts at the fith character (which is 4 since the string starts with zero), and uses the next 4 characters. This function can be quite handy when you are trying to get part of a string later.