Thanks for submitting the correct answer :) hehe.

But you used it in an incorrect way. If the third argument is 1, it's effectively a noop. The third argument does not mean to discard everything after the first field.

    my ($y) = split " ", "a b", 1;
    print $y;
will print a b, and not a.

If you want to use only the first field, and use a third argument, just use:

    my ($y) = split " ", $string, 2;
That's right. No indexing required. But even the limit isn't required. Just the simple:
    my ($y) = split " ", $string;
will do. And because it is so simple, Perl can optimize that. Here's a benchmark program (there are brackets where indexing is used - for some reason, perlmonks strip them), and the results:
#!/opt/perl/bin/perl -w

use strict;
use Benchmark;

my $str = "a " x 6;

timethese -100 => {           
    index   =>  sub {my ($y) = (split " " => $str) [0]},
    regex   =>  sub {my ($y) = $str =~ /(\S+)/},
    limit   =>  sub {my ($y) = (split " " => $str, 2) [0]},
    plain   =>  sub {my ($y) =  split " " => $str},
}

__END__
Benchmark: running index, limit, plain, regex, each for at least 100 CPU seconds...
index: 125 wallclock secs (105.53 usr +  0.00 sys = 105.53 CPU) @ 34487.35/s (n=3639450)
regex: 121 wallclock secs (105.06 usr +  0.00 sys = 105.06 CPU) @ 43695.61/s (n=4590661)
limit: 123 wallclock secs (104.03 usr +  0.02 sys = 104.05 CPU) @ 48699.04/s (n=5067135)
plain: 120 wallclock secs (105.18 usr +  0.02 sys = 105.20 CPU) @ 52044.32/s (n=5475062)

The bottom line is, if you want Perl to do the optimizing, keep your code simple.

-- Abigail


In reply to RE: Using the third arguement for split by Abigail
in thread is split optimized? by Anonymous Monk

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.