Tweet

How can I access the individual characters in a string?

Before answering this faq, we ask that you consider the following question.

    Should you be accessing the individual characters in the string?

It may be that there are more Perl-like ways to solve the problem, that haven't occured to you because you are thinking within the framework of another programming language. In many cases, for instance, you could use Perl's powerful regular expressions for this sort of problem.

However, if your answer is still yes, then there are a few ways to go about it.

Solution 1: split

If you pass no seperator into split, it will split on every character:

    #!/usr/bin/perl
    use strict;
    use warnings;

    my $string = "Hello, how are you?";

    my @chars = split("", $string);

    print "First character: $chars[0]\n";

The output of this program is:

    First character: H

Solution 2: substr

You can access an individual character using substr:

    #!/usr/bin/perl
    use strict;
    use warnings;

    my $string = "Hello, how are you?";
    my $char = substr($string, 7, 1);

    print "Char is: $char\n";

The above code would output:

    Char is: h

Solution 3: Unpack

Like substr, if you want a character from a particular position, you can use unpack:

    #!/usr/bin/perl
    use strict;
    use warnings;

    my $string = "Hello, how are you?";
    my $char = unpack("x9a1", $string);

    print "Char is: $char\n";

The output of this program is:

    Char is: w

Solution 4: substr and map

If you want to access all the characters individually, you can build them into an array (like Solution 1) using substr and map:

    #!/usr/bin/perl
    use strict;
    use warnings;

    my $string = "Hello, how are you?";
    my @chars = map substr( $string, $_, 1), 0 .. length($string) -1;

    print "First char is: " . $chars[0] . "\n";

    exit 0;

The output of this example would be:

    First char is: H

Solution 5: Regular expression

You can use a regular expression to build an array of chars:

    #!/usr/bin/perl
    use strict;
    use warnings;

    my $string = "Hello, how are you?";
    my @chars = $string =~ /./sg;

    print "Fourth char: " . $chars[3] . "\n";

    exit 0;

The output of this program is:

    Fourth char: l

Solution 6: unpack

unpack can also unpack individual chars into an array:

    #!/usr/bin/perl
    use strict;
    use warnings;

    my $string = "Hello, how are you?";
    my @chars = unpack 'a' x length $string, $string;

    print "Eighth char: $chars[7]\n";

    exit 0;

The output would be:

    Eighth char: h

See also

    perldoc -f split
    perldoc -f substr
    perldoc -f pack
    perldoc -f unpack
[Top]