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)?
Use substr with length 1 as in:
$nth = substr($string, n-1, 1);
Also lookup perlmonks for other solutions.
$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:
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
Corollary to the other substr() answers is that you can use it to set values at an index also. It supports this as lvalue or with extra arguments. It's also very similar to splice, which is the same thing, but for arrays.
$string = "hello"; substr($string, 2, 2) = "this works?"; substr($string, 2, 2, "same thing basically"); @a = qw(s t r i n g s a n d t h i n g s); @cut_out = splice(@a, 2, 2); @cut_out = splice(@a, 2, 2, @replacement);