How can I access the individual characters in a string?
Before answering this faq, we ask that you consider the following question.
It may be that there are more perl-like ways to solve the problem, that haven’t occured to you because you are thinking within the framework of another programming language. In many cases, for instance, you could use perl’s powerful regular expressions for this sort of problem.
However, if your answer is still yes, then there are a few ways to go about it.
Solution 1: split
If you pass no seperator into split, it will split on every character:
The output of this program is:
Solution 2: substr
You can access an individual character using substr:
The above code would output:
Solution 3: Unpack
Like substr, if you want a character from a particular position, you can use unpack:
The output of this program is:
Solution 4: substr and map
If you want to access all the characters individually, you can build them into an array (like Solution 1) using substr and map:
The output of this example would be:
Solution 5: Regular expression
You can use a regular expression to build an array of chars:
The output of this program is:
Solution 6: unpack
Unpack can also unpack individual chars into an array:
The output would be: