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)?

Answers


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:

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

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);

Need Your Help

What are the advantages/disadvantages of using the Add-on SDK to develop my Firefox extension?

firefox firefox-addon firefox-addon-sdk

I am developing (yet another) password manager add-on for Firefox. My add-on needs to:

How do I make Eclipse and mvn appengine:devserver talk to each other?

eclipse google-app-engine maven

I am in the process of switching from Google Plugin for Eclipse to the official Google App Engine Maven Plugin.