Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

perl

If I have a Perl string:

$str = "Hello"; 

how can I get a character at a given index similar to charAt(index)?

like image 275
Gdeglin Avatar asked Apr 10 '09 03:04

Gdeglin


People also ask

Which method do you use to get a character at a given index?

Use charAt() to get a character at the specified index in the string. Alternatively, because strings can be treated like arrays, use the index via bracket notation. To get the character code of the character at a specified index, use charCodeAt() . Note that these methods are all getter methods (return a value).

How do you find the character of a string at an index?

The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.

How do I find a character in a string in Perl?

Perl | index() Function This function returns the position of the first occurrence of given substring (or pattern) in a string (or text).

What is $@ in Perl?

$@ The Perl syntax error or routine error message from the last eval, do-FILE, or require command. If set, either the compilation failed, or the die function was executed within the code of the eval.


1 Answers

Use substr with length 1 as in:

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

Also lookup perlmonks for other solutions.

like image 104
dirkgently Avatar answered Oct 01 '22 17:10

dirkgently