Careful... your advice isn't 100% kosher... if I do exactly what you have listed I get a warning:

Scalar value @array[ eval $splice_str ] better written as $array[ eval $splice_str ] at ./foo.pl line 17.

Which is never really a good thing... we want to stay away from error messages as best as we can :) The best solution then is to wrap the eval in ( ), I wrote up some quick code to benchmark both situations:

#!/usr/bin/perl -w use vars qw/@splice_array $splice_str @array/; use strict; use Benchmark; my @splice_array = (2, 3..7); my $splice_str = "2, 3..7"; my @array = (1 .. 10); sub with_array { return @array[@splice_array]; } sub with_string { return @array[ (eval $splice_str) ]; } timethese (-5, { "array" => \&with_array, "string" => \&with_string, });
and the results... were... well, very within what we would have expected them to be :)
Benchmark: running array, string, each for at least 5 CPU seconds... array: 0 wallclock secs ( 5.02 usr + 0.00 sys = 5.02 CPU) @ 54 +8512.95/s (n=2753535) string: 6 wallclock secs ( 5.29 usr + 0.00 sys = 5.29 CPU) @ 56 +98.87/s (n=30147)
so, the array slice version is only a factor of 100 faster :)

In reply to RE: RE: Splicing an array. by eduardo
in thread Splicing an array. 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.