Perl programming: string conversion to character array
Tutoring programming, conversions between strings and arrays are relevant. The tutor shows an easy way to do it in Perl.
Converting a string to a character array is a common task in small programs, especially ones that accept user input. While some languages have a built-in function, often named toString() or something similar, Perl has none I know of.
The conversion is easy to do in Perl nonetheless, using Perl’s built-in split(/separator/, $inputstring) function, which takes the $inputstring and breaks it apart at the separators, or just character by character if no separator is given. The resulting characters can be fed, one by one, into an array:
#!/usr/bin/perl
print “Please enter a string.”;
$userstring=<STDIN>;
@arra=split(//,$userstring);
$i=0;
while($arra[$i]){
print “Character $i in your new array is “.$arra[$i].”\n”;
$i++;
}
There are a couple of “finer points” in these lines of code. I’ll be talking about them in future posts:)
Source:
Jack of Oracle Tutoring by Jack and Diane, Campbell River, BC.
Leave a Reply
You must be logged in to post a comment.