Perl string processing FAQ: How can I process every character in a Perl string?
I recently had to write some Perl code to process every word in a file, and that made me wonder how to process every character in a Perl string. I didn't know how to do this, but I just cracked open my copy of the Perl Cookbook, and found a couple of possible solutions.
Split each Perl string character into an array
One approach you can take to process every string character is to break your Perl string into an array, like this:
# our string $string = 'Four score and seven years ago our fathers'; # split the string into an array of characters @array = split(//, $string); # print the contents of our perl array print "@array";
The output from that simple Perl script looks like this:
F o u r s c o r e a n d s e v e n y e a r s a g o o u r f a t h e r s
(I added a carriage return in there to keep the text from scrolling.)
Perl string character processing - Split a string into characters and print
If you don't want/need to use a Perl array while processing each character, you can split the string into characters in a Perl for loop, like this:
# define our string $string = 'Four score and seven years ago our fathers'; # print each character in the string foreach $char (split //, $string) { print "$char "; } # print a newline at the end print "\n";
More Perl string character processing examples
The Perl Cookbook shows a couple of other ways you can tackle this problem, but I think these are the easiest (or most obvious) approaches to process every character in a Perl string.