How can I get a character at a given index in Perl?

$char = substr( $mainstring, $i , 1 );

Is one way to do it, probably the clearest.

If what you were wanting was the numeric value and you were intending to do this lots:

unpack("W*","hello")

Returns an array of Char values:

print join ",", unpack("W*","hello")  ; 
#  104,101,108,108,111

For proper Unicode/Utf8 stuff you might want to use

use utf8;
unpack("U*","hello\0ƀ\n") 
# 104,101,108,108,111,0,384,10

Use substr with length 1 as in:

$nth = substr($string, n-1, 1);

Also lookup perlmonks for other solutions.

Tags:

String

Perl