Perl substr example - How to extract a substring from a string

Perl substring FAQ: How do I extract a substring from a string?

Solution: Use the Perl substr function. The general substr syntax looks like this:

$my_substring = substr($full_string, $start_pos, $length);

Perl substring example (substr)

A more specific Perl substring example is shown in the following code, where I extract the $firstname and $lastname strings from the $name string:

$name = "alvin alexander";
$firstname = substr($name, 0, 5);
$lastname = substr($name, 6, 9);

print "first name: $firstname\n";
print "last name:  $lastname\n";

If I take that code and place it in a file named sub.pl, and then run it through the Perl interpreter, the output looks like this:

$ perl sub.pl 
first name: alvin
last name:  alexander

Perl substr - things to remember

The most important thing to remember is that the starting position is a zero-based number, so when I grabbed my first name from the string, like this:

$firstname = substr($name, 0, 5);

I used the number 0 as my starting position, as that represents the first character in the string.

 

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.