Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

RE: Splicing an array.

by nuance (Hermit)
on Aug 13, 2000 at 06:37 UTC ( #27676=note: print w/replies, xml ) Need Help??

in reply to Splicing an array.

You are trying to take an array slice with a string, the punctuation prevents it being converted to a number.

you could do this:

Updated to fix silly typo as pointed out by Kozz below

my @splice_array = (2, 3..7); print @array[@splice_array];
the problem is that you want the "string" to be expanded to a list and that won't happen with your current method. If you really want to use the string, then you have to eval it, as this will cause it be be expanded into a list, thus:
my $splice_str = "2,3..7"; print @array[eval $splice_str];
but that's probably grossly inefficient.


Replies are listed 'Best First'.
RE: RE: Splicing an array.
by eduardo (Curate) on Aug 13, 2000 at 08:16 UTC
    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 ./ 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 :)
(Kozz)RE: RE: Splicing an array.
by Kozz (Friar) on Aug 13, 2000 at 08:18 UTC
    Just fixing a typo in nuance's first solution. I think he meant
    my @splice_array = (2, 3..7); print @array[@splice_array];

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://27676]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (1)
As of 2022-01-25 16:09 GMT
Find Nodes?
    Voting Booth?
    In 2022, my preferred method to securely store passwords is:

    Results (67 votes). Check out past polls.