No elegant alternative. As I showed in the benchmark, this works fine:
sub splt{split" ",reverse((split" ",(reverse$x),1)[0]),1;};
The most elegant approach to this problem is the use of tr function. The implementation below beats regex three times and can be made faster by trivial extension of tr function mentioned in my prev post (something like option 'x' -- stop the translation on the first symbol outside the
set1 and return this position), which can be used instead of more general function
index for searching single characters in the string and can made like rindex to be able to search in reverse direction too.
Looks like the solution for trim from the Cookbook mentioned by Fletch along with potentially deforming the string is slower then regex in my test(on my machine it took 3.56 sec real time).
Here is the "tr based" algorithm for trim:
time perl -e 'for (1..1000000) { $line=" aaa bbb ccc ddd eee fff "; $_=$line; $_=~tr/ /x/c; $start=index($_,'x'); $line=substr($line,$start,rindex($_,'x')-$start+1); }'
real 0m1.112s
user 0m1.076s
sys 0m0.031s
Can be made into a single statement making it slightly( ~7%) slower:
$line=substr($line,($start=index($_=$line=~tr/ /x/cr,'x')),rindex($_,'x')-$start+1);
# time perl -e 'for (1..1000000) { $line=" aaa bbb ccc ddd eee fff "; $line=substr($line,($start=index($_=$line=~tr/ /x/cr,'x')),rindex($_,'x')-$start+1); }'
real 0m1.189s
user 0m1.154s
sys 0m0.015s
-
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.