Iterating a string through each character
In general if there is a need for us to iterate though a string character by character, then we normally split the string using a statement like:@chars=split("",$var);
Now after the array is created we iterate through that array.But an easy way of doing this in Perl without creating an array is :
while ($var =~ /(.)/sg) {
my $char = $1;
print $char."\n"
}
Below is the explanation for the same:$var =~ /(.)/sgMatch any character though out the string and round braces "()" captures the matched character.
/s
Treat string as single line. That is, change "." to match any character whatsoever, even a newline, which normally it would not match.
/g
Match all occurrences of the regexp throughout the line instead of only the first occurrence.
.png)







I am a software programmer working in India. I usually like to blog in my free time.
0 comments: