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

How would one go about getting the first char of a scalar string? For example:

my $test = "Hello World!"; print $test[0];
(That's what I would do in Python, with Python syntax of course).

What is the best way to do this in Perl?

Replies are listed 'Best First'.
RE: first char of string?
by vroom (His Eminence) on Mar 11, 2000 at 03:31 UTC
    take a look at the substr function it's usage is as follows: to get at it you just do something like:
    substr($mystring,0,1); #the first parameter is your string.. the second is the start index, a +nd the third is the length of your substring


    vroom | Tim Vroom | vroom@cs.hope.edu
Re: first char of string?
by Anonymous Monk on Mar 13, 2000 at 11:20 UTC
    You could use a regex as well:
      $_="Hello World!"; $_ =~ /^(.)/; print "The first character is: $1\n";
    This will snag any character, including embedded tabs, newlines, etc, etc. However, it is not as efficient as using substr (substr is a bit more than twice as fast in my tests).
RE: first char of string?
by Anonymous Monk on Mar 11, 2000 at 03:27 UTC
    To get the first character of a string, use substr() my $test = "Hello World!"; print substr($test,0,1);
RE: first char of string?
by Anonymous Monk on Mar 11, 2000 at 10:07 UTC
    The easiest way would be to pull a substring of the scalar, thusly: $string = "I *AM* the binary bitch goddess!"; $test_string = substr($string,0,1); print $test_string;
Re: first char of string?
by Anonymous Monk on Mar 13, 2000 at 10:51 UTC
    Since everyone has given the direct answer, here a few other ways of doing it:

    Regex:

    $string =~ m!^(.).+$!;
    my $first = $1;

    Split:

    my @list = split('', $string); # I can't recall if '' works
    $list[0]; # but I think that is right.

    Really funky:

    $string = reverse($string);
    my $char = chop $string;
    # and if you need the string intact still
    $string .= $char;
    $string = reverse($string);

    There is more than one way to do it.

      you could do it even shorter: ($char) = split("",$string);