substr Function in Perl

What is substr Function in Perl?

Explanation

This is used to return a substring from the expression supplied as it's first argument.

Syntax:


substr EXPR,OFFSET,LENGTH,REPLACEMENT
substr EXPR,OFFSET,LENGTH
substr EXPR,OFFSET

In the above syntax's, "EXPR" is the string, "OFFSET" is the starting of the substring inside the string, "Length" specifies the length from the offset to the end of the string, "REPLACEMENT" specifies the string to be replaced with the substring.

Example :


#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
$s = "hi how are you";
$str = substr ($s,3,,);
print "String printed from the offset 3: $strn";
print "<br>";
Result :

String printed from the offset 3: how are you

In the above example the string, from the third index is printed,"length","replacement" string arguments are not sepcified to print the string.

Example :


#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
$s = "hi how are you";
$str = substr ($s,3,3,);
print "String printed from the offset 3: $strn";
print "<br>";
Result :

Printed string with offset 3,upto length 3: how

In the above substr function example,we have specifed the length as "3" apart from the offset "3", so only the string "how" is printed.

Example :


#! C:programfilesperlbinperl
print "content-type: text/htmlnn";
$s = "hi how are you";
$str = substr ($s,3,3,where);
print "Printed string 'how' replaced with 'where': $sn";
Result :

Printed string 'how' replaced with 'where': hi where are you

In the above substr function example, we have kept the "offset" and "length" same, but here we have added a string to replaced where the string "how" is replaced with the string "where".

Ask Questions

Ask Question