In perl, the substr function can be used to access individual characters or a portion of a string. The syntax of substr function is as follows:

substr ( string, offset [, count] )

Arguments:

  • string – string from which you would like to extract a sub-string
  • offset – this indicates start of the sub-string you want to extract
  • count – length of the sub-string to extract

A negative number also can be specified for “offset” argument that make substr to count the characters in the reverse direction (i.e from the end). If “0″ is specified as offset, sub-string is extracted from beginning of the string. If a positive value is given, number of characters are counted from the beginning.

The “count” argument is optional and assumed to be till the end of string if not specified.

The following example shows various ways of using substr function in perl.

#!/usr/bin/perl

$str="What goes around comes around";

print substr($str, 0, 1) . "\n";
print substr($str, 5, 4) . "\n";
print substr($str, 17) . "\n";
print substr($str, -1) . "\n";
print substr($str, -6) . "\n";
print substr($str, -12, 5) . "\n";

The output of above perl script would be:

[neo@techpulp ~]# perl substr.pl
W
goes
comes around
d
around
comes
[neo@techpulp ~]#