matthxx has asked for the wisdom of the Perl Monks concerning the following question:

I have a problem that I've been stuck on for a couple of days. I suspect the answer is a embarrassingly simple but it's driving me around the bend. How do I extract the first character of a string?

Replies are listed 'Best First'.
Re: String extraction
by FunkyMonk (Bishop) on Aug 30, 2007 at 18:19 UTC
    You want a substring of a string? Use substr
    my $letter = substr $string, 0, 1

Re: String extraction
by suaveant (Parson) on Aug 30, 2007 at 18:20 UTC
    substr
    my $chr = substr($str,0,1);
    ord will do it, too, but returns the ascii value of the first char of the string.

                    - Ant
                    - Some of my best work - (1 2 3)

Re: String extraction
by dsheroh (Monsignor) on Aug 30, 2007 at 19:44 UTC
    You could also use
    $string =~ /^(.)/; $first_char = $1;
    or
    @chars = split //, $string; $first_char = @chars[0];
    or
    $first_char = unpack 'a', $string;
    but, in general, substr is the better option.
      Or even
      my $first_char = (split //, $string)[0];

Re: String extraction
by gloryhack (Deacon) on Aug 30, 2007 at 18:22 UTC
    #!/usr/bin/perl use strict; use warnings; my $string = 'This is my string.'; my $first_char = substr($string, 0, 1); print "My first character is $first_char\n";
Re: String extraction
by ikegami (Patriarch) on Aug 30, 2007 at 18:41 UTC