Basic String ManipulationPerl is the absolute King when it comes to parsing, dicing, chopping, and manipulating strings of characters. Most of this power comes from its regular expressions but there are a few simpler functions that you should know about.How Long?The 'length' function simply returns how long the string is - how many characters the string has in it. Spaces and punctuation count as characters too!$s = "Now is the time to party."; $l = length($s); # gets 25 ?? 550 116
Where Is?The 'index' function looks for the first occurence of one string in another and returns where it found it. Both strings may be a variable or a string constant.$s = "Now is the time to party."; $i = index $s, "ti"; # searches $s for the string "ti" Indices start at 0:
So "ti" starts at index 11.
If the string is not found, index returns -1.
It helps to draw pictures of strings with each character in a little box. And numbers on the boxes indicating the indices. It helps in counting and figuring. Take This PartTaking portions of a string with the function 'substr':The second parameter of substr tells which index to start at and the third tells how many characters to take. More examples:$s = "Now is the time to party."; $t = substr($s, 11, 7); # gets "time to" print substr $s, 7, 3; # the print substr $s, 19, 1; # p 182-183 561 208
Longer ExampleLet's see how we can use length, index and substr to count how many t's there are in a string:
Substr ShortcutsWith substr there are several shortcuts to help. If the second parameter (the index of where to start) is negative then counting begins at the end. The last character in the string is at index -1.If the third parameter of substr (the number of characters to take) is omitted it will take everything to the end of the string. $s = "hello there sweety"; print substr $s, -3; # prints "ety" Exercises
|