Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

Re: Data structures in Perl. A C programmer's perspective.

by davido (Archbishop)
on Sep 06, 2013 at 17:08 UTC ( #1052744=note: print w/replies, xml ) Need Help??

in reply to Data structures in Perl. A C programmer's perspective.

You might enjoy Mastering Algorithms with Perl, from OReilly. It's a little old, but good algorithms and datastructures are mostly timeless. The book does a nice job of presenting data structures and algorithms in Perl... even if the Perl spoken is from the early 2000's.

Yes, Perl has arrays that can do many of the things you might do with a doubly linked list; push, pop, shift, unshift, and splice. But there are tradeoffs in everthing.

A linked list can do inserts in O(1) time. Arrays in Perl can grow substantially without needing to be moved around in memory, but focusing on splice, it's obvious that an insert anywhere aside from the top or bottom of the array is going to consume O(n) time. If you insert a new element between $a[5] and $a[6], you're going to have to shift 6 and everything thereafter to make room, and that's a linear-time operation whether it's being done in Perl or C.

On the other hand, lookups in a linked list are O(n). You can't binary search a linked list. You don't have random-access. Everything search is O(n) unless you maintain some crossreference index, which is basically just throwing another datastructure at the problem.

The main reason that arrays are usually chosen over linked lists in Perl is because arrays are implemented entirely "in Perl's guts", whereas most linked list implementations are in Perl code. So unless the characteristics of the problem are some edge case where you're inserting in the middle of the list frequently but rarely doing searches, arrays will be faster to use.

Trees, on the other hand, are really useful, even in Perl.


Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1052744]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (7)
As of 2018-02-19 16:37 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (266 votes). Check out past polls.