Perl | substr() function

substr() in Perl returns a substring out of the string passed to the function starting from a given index up to the length specified. This function by default returns the remaining part of the string starting from the given index if the length is not specified. A replacement string can also be passed to the substr() function if you want to replace that part of the string with some other substring.
This index and length value might be negative as well which changes the direction of index count in the string.
For example, if a negative index is passed then substring will be returned from the right end of the string and if we pass the negative length then the function will leave that much of the characters from the rear end of the string.

Syntax: substr(string, index, length, replacement)
Parameters:

  • string: string from which substring is to be extracted
  • index: starting index of the substring
  • length: length of the substring
  • replacement: replacement substring(if any)

Returns: the substring of the required length

Note: The parameters ‘length’ and ‘replacement’ can be omitted.

Example 1



filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl
  
# String to be passed
$string = "GeeksForGeeks";
  
# Calling substr() to find string 
# without passing length
$sub_string1 = substr($string, 4);
  
# Printing the substring
print "Substring 1 : $sub_string1\n";
  
# Calling substr() to find the 
# substring of a fixed length
$sub_string2 = substr($string, 4, 5);
  
# Printing the substring
print "Substring 2 : $sub_string2 ";

chevron_right


Output :

Substring 1 : sForGeeks
Substring 2 : sForG 

Example 2

filter_none

edit
close

play_arrow

link
brightness_4
code

#!/usr/bin/perl
  
# String to be passed
$string = "GeeksForGeeks";
  
# Calling substr() to find string 
# by passing negative index
$sub_string1 = substr($string, -4);
  
# Printing the substring
print "Substring 1 : $sub_string1\n";
  
# Calling substr() to find the 
# substring by passing negative length
$sub_string2 = substr($string, 4, -2);
  
# Printing the substring
print "Substring 2 : $sub_string2 ";

chevron_right


Output :

Substring 1 : eeks
Substring 2 : sForGee 


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.