Discussion:
Basic help navigating individual characters of a string
a***@yahoo.com
2008-04-25 10:12:34 UTC
Permalink
Please forgive my ignorance up front. I'm very much a beginner. Ok,
I'm trying to be able to look at the individual characters of a string
with the ultimate hope of being able to parse messages based on a
series of messages of variable length. I thought I had found the
answer with the following text:

use String;

$str = new String("$line[0]");

print "The string is '$str\n";
printf("Length of the string is %d characters\n", $str->length);
printf("The first character of the string is %s\n", $str->charAt(0))

But, when I run the program I get the following error:

Can't locate String.pm in @INC (@INC contains: /System/Library/Perl/
5.8.8/darwin-thread-multi-2level /System/Library/Perl/5.8.8 /Library/
Perl/5.8.8/darwin-thread-multi-2level /Library/Perl/5.8.8 /Library/
Perl /Network/Library/Perl/5.8.8/darwin-thread-multi-2level /Network/
Library/Perl/5.8.8 /Network/Library/Perl /System/Library/Perl/Extras/
5.8.8/darwin-thread-multi-2level /System/Library/Perl/Extras/5.8.8 /
Library/Perl/5.8.6 /Library/Perl/5.8.1 .) at ItchExercise.pl line 8.
BEGIN failed--compilation aborted at ItchExercise.pl line 8.

Is there a substitute I can use? Or can I download something
somewhere?

Help!

And thanks in advance!
Mark J. Reed
2008-04-26 01:40:06 UTC
Permalink
1) Wrong list. This list is for the folks who are currently
implementing the new language Perl 6.
You want ***@perl.org. Send a message to
beginners-***@perl.org to subscribe, and please send any
followups there rather than here.

2) Strings in Perl are not objects, and there is no "String" class -
Perl 5 is simply not that object-oriented. You don't say $str = new
String("blah") (which would be redundant even in Java and Javascript,
since the literal already constructs an object); you just say $str =
"blah". Anyway, it looks like you already have a string variable in
your example, namely $line[0].

3) Since strings aren't objects, you don't call methods on them; you
use functions instead. So it's not $str->length, but length($str).

4) There's no distinction between characters and strings in Perl;
strings are not considered to be a collection of characters, but
rather a fundamental type. So you can't index into the string.
Instead, use the substr() function to pull out a substring of length
1:

printf "The first character of the string is '%s'\n", substr($str,0,1);

Also, since print() takes multiple arguments and concatenates them,
and you can interpolate variables in strings, you don't need printf
most of the time:

print "The first character of the string is '", substr($str,0,1), "'\n";

...although it is arguably clearer in this case.
--
Mark J. Reed <***@gmail.com>
Loading...