in reply to Matching First Character of Strings Efficiently

If we play with the definition of "first character", Perl will match a number at the beginning of a string:

$_ = "13foo"; if($_ == 13) { print "Works\n"; } __OUTPUT__ Works

But doing it under warnings gives you Argument "13foo" isn't numeric in numeric eq (==). The ++ operator also has some DWIM magic involved for incrementing strings that begin with numbers (but -- doesn't).

For any strings, you can also use split like this:

my ($first, $rest) = split '', $str, 2;

You can also play string reversal tricks, if you don't mind modifying the string:

$_ = reverse $str; print chop;

----
: () { :|:& };:

Note: All code is untested, unless otherwise stated

Replies are listed 'Best First'.
Re: Re: Matching First Character of Strings Efficiently
by Limbic~Region (Chancellor) on Mar 15, 2004 at 19:58 UTC
    hardburn,
    I did say first letter, not "first character". Regardless, your first proposal will not work because it is checking one string against a hard coded value. The requirement is to test the first letter/character of one string against the first letter/character of a second string.

    I will add your split solution to the benchmark.

    While I did not explicitly state modifying the string is not allowed, the expensive_function will not work unless the strings were "as received". I will however add this solution to the benchmark by appending the chop'd character back on to the re-reversed string.

    Cheers - L~R