Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
Some might consider using split and an index. The problem with this solution is that it's really slow, particularly as the string gets longer.

Here's some benchmarking code that'll show you:

#!/usr/local/bin/perl -w use strict; use Benchmark; use vars qw/$str/; $str = "123456789asgdjlaskjglkajblnlbnlaqjteoijqotijwojgl;akjglkj"; timethese(shift || 10000, { 'unpack' => sub { my $char = getn_unpack($str, 30) }, 'substr' => sub { my $char = getn_substr($str, 30) }, 'split' => sub { my $char = getn_split($str, 30) } }); sub getn_unpack { return unpack "x" . ($_[1]-1) . "a", $_[0]; } sub getn_substr { return substr $_[0], $_[1]-1, 1; } sub getn_split { return +(split //, $_[0])[$_[1]-1]; }
And here are the benchmark results:
Benchmark: timing 100000 iterations of split, substr, unpack... split: 20 secs (19.39 usr 0.00 sys = 19.39 cpu) substr: 0 secs ( 1.78 usr 0.00 sys = 1.78 cpu) unpack: 2 secs ( 2.89 usr 0.00 sys = 2.89 cpu)
The substr method is, obviously, the fastest, because that's what it's designed to do, basically.

unpack is also quite fast.
split has to split the entire string, construct an array of length($str) elements, then take an index.

So, the best way is to use substr.


In reply to Re: How do I get the Nth Character of a String? by btrott
in thread How do I get the Nth Character of a String? by vroom

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



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (6)
As of 2024-03-28 12:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found