An alternative approach to reading the first character of a string.

An alternative approach to reading the first character of a string:

$char = chr ord $string;

This is mainly of curiosity value since it would be better in terms of legibility and maintenance to use one of the more standard methods shown below. In particular substr.

Interestingly, albeit moderately, this appears to be faster than some of the other methods.

#!/usr/bin/perl -w use strict; use Benchmark 'cmpthese'; my $str = "some string here"; cmpthese( 500000, { 'pop_chord' => sub { pop_chord($str) }, '_substr' => sub { _substr($str) }, '_unpack' => sub { _unpack($str) }, '_match' => sub { _match($str) }, } ); sub pop_chord { chr ord pop } sub _substr { substr pop,0,1 } sub _unpack { unpack"a",pop } sub _match { (pop=~/(.)/s)[0] } __END__ Benchmark: timing 500000 iterations of _match, _substr, _unpack, pop_chord _match: 3 secs (3.22 usr + 0.01 sys = 3.23 CPU) @ 154798.76/s _substr: 0 secs (0.85 usr + 0.00 sys = 0.85 CPU) @ 588235.29/s _unpack: 2 secs (2.04 usr + 0.00 sys = 2.04 CPU) @ 245098.04/s pop_chord: 1 secs (0.73 usr + 0.00 sys = 0.73 CPU) @ 684931.51/s Rate _match _unpack _substr pop_chord _match 154799/s -- -37% -74% -77% _unpack 245098/s 58% -- -58% -64% _substr 588235/s 280% 140% -- -14% pop_chord 684932/s 342% 179% 16% --

In reply to Read the first character of a string by jmcnamara

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.