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

Re: How do I insert an element into an arbitrary (in range) array index?

by lhoward (Vicar)
on Sep 04, 2000 at 00:07 UTC ( [id://30943]=note: print w/replies, xml ) Need Help??


in reply to How do I insert an element into an arbitrary (in range) array index?

By insert I assume you mean "put between 2 current array elements, shifting down the later ones to make room".

The unfortunate answer is that you can't do this efficiently using native perl arrays. The code to do it isn't long or complex, but as a consequence of the design of perl's arrays (which makes them so efficient at so many other operations) sacrifices had to be made. One of those is that inserting in the middle of an array is "slow" — the time it takes to do it depends on how many elements are already in the array. (In big-O notation, the operation is said to be O(n).).

my @array = qw(3 1 4 1 5 9 2 6 5 4); my $offset = 5; my $value = 'abc'; print "before: @array\n"; splice @array, $offset, 0, $value; print " after: @array\n";
  • Comment on Re: How do I insert an element into an arbitrary (in range) array index?
  • Download Code

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (5)
As of 2024-04-24 22:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found