in reply to Re: Perl vs C
in thread Perl vs C

There is no need for a "linked list" in Perl! A Perl list does what a C linked list can do and more!

Fond as I am of shiftily pushing and popping in Perl, I simply have to disagree with this.

For example, one nice property of a linked list that isn't shared by what you call Perl lists is that pointers into it are not invalidated by insert/delete operations elsewhere.

(This is actually a real-world example that has bitten me just this week: I have a list of properties, and a bunch of objects that each need to access all properties up to and including a certain point. The implementation stores the properties in an array and simply has the objects hold the index of the last property they need. Now suddenly I have a new requirement to insert properties at arbitrary positions in the list, and that means I potentially have to change the indices stored by every object. If I'd been using a linked list, I'd have got the correct behaviour by default. I'm sorely tempted to redo it that way ...)

Replies are listed 'Best First'.
Re^3: Perl vs C
by Tanktalus (Canon) on Mar 14, 2009 at 21:19 UTC

    That depends on how you define "pointers."

    If you're simply doing Node* n = &currentNode; in C, then that works fine in perl, too: my $ref = \$list[$n];. Now, granted, in C, you know what's next and what's before (assuming doubly-linked), but I have to admit to not needing that very often. And, besides, you can create a linked list in Perl, too, if that's what you really want. Each node is just an array, where the first element (0) is a reference to the data, the second is a reference to the previous node, and the third is a reference to the next node.

    If, however, your pointer in Perl is an index, well, yes, that's silly. You don't take an index of your linked list in C, so comparing them isn't quite fair. Of course, if you're using a STL linked list, then you can take an index, but you don't. Well, not if you expect it to survive insert/delete operations elsewhere.

    Like I said, I don't find the need for surviving insert/delete operations too often. I usually use map to transform list A to list B, and survivability is moot. Generally, my object is either transforming a list (usually via map), or my object cares about a particular value/object (which I can retain via reference or copy, as is appropriate). Doing both at the same time is pretty rare. I suppose I've just changed my thinking ("paradigm shift") to fit idiomatic perl. Works for me and my little projects ;-)