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

I've used:
($letter) = $string =~ /^(.)/;
but maybe a simple substr would be better way? Currently I'm too fascinated by regexps, so sometimes it's hard to think about something other :)

Replies are listed 'Best First'.
Re: What's the best way to get first character of the string?
by busunsl (Vicar) on Nov 08, 2001 at 14:01 UTC
    $letter = substr($string, 0, 1);

    It's faster (about four times) and easier to understand.

Re: What's the best way to get first character of the string?
by demerphq (Chancellor) on Nov 08, 2001 at 14:59 UTC
    Well, as lestrrat and busunsl said you can use substr to do this. I just wanted to say however that there are subtle differences between the two choices. Consider this:
    $_="\n"; my ($letter) = /^(.)/; print "Regex: '$letter'\n"; $letter=substr($_,0,1); print "Substr:'$letter'\n";
    The two do not produce the same results. Something to consider when you do convert, but not something to keep you from doing so. Using a regex for this type of task is incredible inefficient in comparison to substr.

    Yves / DeMerphq
    --
    Have you registered your Name Space?

Re: What's the best way to get first character of the string?
by lestrrat (Deacon) on Nov 08, 2001 at 14:01 UTC

    If you really just want to get the first character, I'm sure  substr( $str, 0, 1 ) would be sufficient

TMTOWTDI is your friend!
by dragonchild (Archbishop) on Nov 08, 2001 at 20:05 UTC
    • my $first = substr $string, 0, 1;
    • my $first = substr reverse($string), -1;
    • my ($first) = $string =~ /^(.)/sm;
    • my $first = (split //, $string)[-1];
    • my $first = (reverse(split //, $string))[0];
    • my $first = unpack 'a', $string;
    Now, of course, some of these are more equal than others. Some are more cryptic than others. Some are also slightly more destructive than others. Take your pick. *grins*

    Interestingly enough, the following does not work ...

    my ($first) = reverse($string) =~ /(.)$/sm;

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

Re: What's the best way to get first character of the string?
by mandog (Curate) on Nov 08, 2001 at 20:40 UTC
    substr is probably the way to go.

    For completeness, unpack should probably be put on the long list of other ways to do it.

    my $str="hello world\n"; my $lchar=unpack('A1',$str); print "$lchar \n";


    email: mandog