Gdeglin
Gdeglin

Reputation: 12618

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

Upvotes: 46

Views: 62956

Answers (4)

Siddharth Kumar Shukla
Siddharth Kumar Shukla

Reputation: 137

To get a character at the ith index, use substr. To fetch the 2nd index character, for example:

$str="Perl";
print substr($str,2,1). 

This will give the output r.

Upvotes: 0

jettero
jettero

Reputation: 845

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

Upvotes: 4

Kent Fredric
Kent Fredric

Reputation: 57374

$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

Upvotes: 25

dirkgently
dirkgently

Reputation: 111200

Use substr with length 1 as in:

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

Also lookup perlmonks for other solutions.

Upvotes: 52

Related Questions