Question
How can I get a character at a given index in Perl?
If I have a Perl string:
$str = "Hello";
how can I get a character at a given index similar to charAt(index)?
45 61845
45
Question
If I have a Perl string:
$str = "Hello";
how can I get a character at a given index similar to charAt(index)?
Solution
Use substr
with length 1 as in:
$nth = substr($string, n-1, 1);
Also lookup perlmonks for other solutions.
Solution
$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