How do you retrieve a char from a string?

T

Thierry

I have the following string:

my $greet = "hello";
print $greet[0]."\n";

The above clearly doesn't work since $greet is not an array. Is there
an easy way to access characters at specific index in a string without
losing $greet as a String?

Thierry
 
M

Mirco Wahab

Thierry said:
I have the following string:

my $greet = "hello";
print $greet[0]."\n";

The above clearly doesn't work since $greet is not an array. Is there
an easy way to access characters at specific index in a string without
losing $greet as a String?

The canonical method is the one Sherm already mentioned,
but(!):

...
my $greet = 'hello';

#0
print substr($greet, 0, 1), "\n";

#1
print $greet =~ /.(.)/, "\n";

#2
print +(split //, $greet)[2], "\n";

#3 (only 8bit chars)
print chr( vec $greet, 3, 8 ), "\n";

#4 (trounce and print last char)
print chop $greet, "\n"

Regards

M.
 
A

anno4000

Sherm Pendley said:
Thierry said:
I have the following string:

my $greet = "hello";
print $greet[0]."\n";

The above clearly doesn't work since $greet is not an array. Is there
an easy way to access characters at specific index in a string without
losing $greet as a String?

print substr($greet, 0);

That's the entire string. The first character is "substr($greet, 0, 1)".
See "perldoc -f substr" for details.

I'll refrain fom commentig :)

Anno
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top