FreeKB - Perl Cut a string into pieces (substr)
Perl - Cut a string into pieces (substr)

The substr operator can be used to split or cut a string into pieces. For example, let's say you have a variable that contains the text Hello World.

my $string = "Hello World";

 

substr can be used to cut this string into pieces. In this example, character 1 (the H in Hello) will be replaced with the letter A.

substr($string, 0, 1) = "A";

 

In this example, the $greeting variable will contain the text "Hello" and the $planet variable will contain the text "World".

  • In the $greeting variable, 0 means "start at the beginning of the string" and 5 means "get five characters".
  • In the $planet variable, 0 means "start at the fifth character of the string" and 5 means "get five characters".

 

my $greeting = substr $string, 0, 5;
my $planet   = substr $string, 5, 5;

 


Reverse Order

The following can be used to read the string from right to left. In this example, the $last_character variable will contain "d", which is the letter "d" in World.

my $last_character = substr $string, -1, 1;

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter cb03d in the box below so that we can be sure you are a human.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |