Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

Perl vs C

by santhosh_89 (Scribe)
on Mar 14, 2009 at 05:50 UTC ( #750575=perlquestion: print w/replies, xml ) Need Help??
santhosh_89 has asked for the wisdom of the Perl Monks concerning the following question:

How can I connect C program with Perl

Replies are listed 'Best First'.
Re: Perl vs C
by GrandFather (Sage) on Mar 14, 2009 at 06:28 UTC

    Perl is a sophisticated interpreted language providing rich facilities for data manipulation out of the box. Many people refer to it as a "high level" language for that reason and because it uses reference counted memory management. It has inherited large components of its syntax from C and large chunks of its richness from several other languages. It provides dynamically typed scalar variables, dynamically sized arrays of scalars, hashes of scalars keyed by strings and a variety of more exotic scalar types. Perl does not provide pointers, but scalars may be assigned references to various entities (including arrays, hashes and subroutines). Perl is written in C and is relatively easily ported to new systems. Perl applications can be highly portable including between different operating systems.

    C is a simple compiled language providing a small number of fundamental types and no I/O at all. Much of C's utility is provided by a fairly standard set of functions supplied in the C Runtime Library (CRL) along with the compiler. C provides a rich set of arithmetic and logic operators (which Perl inherits). C does not provide any dynamic data structures (not even a string type), although the CRL provides ways of allocating and disposing chunks of memory under programmer control. C provides various integer types, fixed size arrays, structs, unions and pointers. C is easy to implement on new systems and is thus often the language of choice for bootstrapping new systems. C applications can be highly portable but tend to be more affected by CRL implementation details than Perl.

    True laziness is hard work
      The only two languages I know with any proficiency are perl and C. I started with perl (after shell scripting and html/javascript stuff) and then decided to learn C, which is probably common (I imagine it is also common the other way around, but I bet the desire to "move downstream" is a More Significant Factor).

      ?"vs."?: I might guess that they are in fact as different from one another as you could get, despite all the similarities. Perhaps this is why you see such a proliferation of perl variants (php, ruby) alongside the proliferation of C variants and stuff grounded in C, like perl itself. But "the ground" of C is really memory management, which is fundamental to everything; learning perl, it is not much of an issue initially; learinging C it is the issue initially.

      Anyway, thanks Grandfather for those two cents :) The only phrase that gave me pause is "no I/O at all", which seems oxymoronic no matter what (intuitively speaking), tho I won't argue the point further.

      ps. I just noticed the rest of the thread! I have not been using this forum in a while and got I will leave it at that and start reading, it is a topic close to my heart :)

        There is a hard to make distinction between the C language and the almost universal set of functions provided through libraries. Try using C without any #include statements and see just what isn't there - printf for a start. The same is true for many languages of course. Consider what you actually get as part of the Java language when you take out the "libraries".

        True laziness is hard work
Re: Perl vs C
by targetsmart (Curate) on Mar 14, 2009 at 06:24 UTC
    Perl is written in C.

    If you want to utilize pure speed of the processor, If you have enough time and knowledge on C you can very well code/achieve everything using C. In C you have to manage the memory(allocation/deallocation) mistakes there will often lead to SEGMENTATION FAULT.

    If you want the speed of C, with lots of flexibility in using/manipulation of data structures, if you want pick-up and use third party modules, with lots and lots of support & help from community(perlmonks) then perl is best. Whatever is possible to be achieved using C is achieved using perl also. Perl manages memory for you, but still you got to be careful on using the created data structures/variables otherwise you will end up in using all the available memory, I have been using perl for 4 years now and I have never got a SEGFAULT :) .

    I compared only the points that suddenly struck my mind, I think there are so many of them like this.
    Good question.

    -- In accordance with the prarabdha of each, the One whose function it is to ordain makes each to act. What will not happen will never happen, whatever effort one may put forth. And what will happen will not fail to happen, however much one may seek to prevent it. This is certain. The part of wisdom therefore is to stay quiet.
      "Whatever is possible to be achieved using C is achieved using perl also.

      Don't be insane. This is so obviously far from the truth as to be ridiculous.

      Perl is beautiful but SPECIALIZED. You will (almost) never realize the execution speed of C in perl which is why people do not write (eg) 3D API bindings for perl.

      What is the acronym for again, anyway?
        You will (almost) never realize the execution speed of C in perl....

        That depends on what you're doing. If you want to compare the languages themselves (okay, you can use C's standard library), I can suggest several algorithms and data structures and tasks which will be as fast in Perl as in C.

        ... which is why people do not write (eg) 3D API bindings for perl.

        A far larger problem is data marshalling instead of opcode dispatch.

        What is the acronym for again, anyway?

        Perl is not an acronym.

        people do not write (eg) 3D API bindings for perl.

        Oh really?

        Of particular interest:

        Due to Perl's strength in string manipulation, there are cases where Perl can even outperform C when loading/manipulating shader programs.

        I wrote bindings for OGRE. I found them to be fairly fast, actually, though of course most of the execution is done in C++ land.

        You probably don't mean Perl specifically, but interpreted languages generally. But from what I see, a lot of times there are no bindings for Perl when there are for Python and Ruby. I think the reason for not writing bindings is not the speed (Perl is probably faster than Ruby, I don't know about Python) but rather the ease of writing the bindings. For example, for Python there is Py++; we don't have the equivalent of that for Perl.

Re: Perl vs C
by Marshall (Monsignor) on Mar 14, 2009 at 13:23 UTC
    I was just working on a C project this evening with arrays of pointer to structs and linked lists of structs that point to more structs, etc. This gets pretty messy in C! Here are some observations about the transition from C to Perl.

    1. Coding effiency is about 5-10x. A well written Perl program will be far shorter than the equivalent thing in C. Sometimes stunningly so if you are on the right job for Perl. Execution effiency is maybe 1/3 or less than that of C, but often it is possible to implement a far more sophisticated algorithm in Perl that will make up a lot of that. There are an enourmous number of modules in the public domain that you can use! The mileage varies: some of these are really great, some are not so great. Also with Perl it is far easier to create complex dynamic data structures.

    2. One fundamental roadblock to good Perl is mis-understanding of Perl lists and how to use them. A Perl list is not a C array! (An aside: One author says that the variable that defines a Perl list is an array, an array variable of a Perl list. I think that is confusing!). Don't equate Perl lists with C arrays! The sooner you get over that the better!

    - There is no need for a "linked list" in Perl! A Perl list does what a C linked list can do and more! I guess one analogy could be that list oriented Perl functions operate on the C equivalent of linked lists. Say, you want to navigate a C linked list of something simple, a linked list of structs which have a simple int and a next pointer and remove all things in that list don't match some criteria for the number, In C this gets messy. In Perl, this is: @num_list=grep{$_ >2}@num_list;.

    The Perl case of LoL (List of List) or LoH (List of Hash) is only very slightly more complex syntax.

    In case of a "simple" C array, if you want to "delete",item [3] in the array! How do you plan to "shrink" that thing?
    - A Perl list is even better than a C linked list because each individual thing in a Perl list can be accessed,removed or added with an index. This feature is WAY over used by beginners. But you can remove or add things the list via an index. A subscript like [2]is seldom needed! Way cool!

    So you should think of a Perl list more like a C linked list. It has those properties as well as C array properties.

    3. Perl can have multiple lvalues! WOW!
    This is a LISP like feature. This is VERY powerful when combined with the Perl idea of a list "slice", like: my($city, $state) = (split(/\s+/,$line))[5,6];. There are a bunch of complications in C with doing something like this. Here is one line that makes it clear that I just need the 6th,7th thing on the space separated line!

    All for now, I will think more about this.

      Coding effiency is about 5-10x.
      Interesting. Someone quantized the coding efficiency. Where do you get the numbers from? Are you quoting a paper? Or did you make them up?
      One fundamental roadblock to good Perl is mis-understanding of Perl lists
      And the most fundamental part of it is not grasping the difference between a list and an array. Which you don't seem to do if I read your post.
      There is no need for a "linked list" in Perl! A Perl list does what a C linked list can do and more!
      There's no "need" for a linked list in C either. Anything done with a linked list can be done in another way in C as well.

      Having said that, one of the attractive things of a linked list is it's O(1) removal of a element (assuming you have a pointer to it). Sure you can delete an element from an Perl array (I think you meant Perl array where you wrote Perl list) - but splicing out an element from an array in Perl takes time linear to the distance of the element to an end of the array (so, linear worst case). Also, adding to a linked list (whether in the middle or the end) is always O(1). But not with Perl arrays (not even when adding at the end - it often can be done in O(1), but if perl needs to realloc the space used for the array, it takes a linear amount of time).

      Considering that people already have take a huge speed and memory hit when picking Perl over C, and that computers nowadays are much faster and have more memory than 30 years ago, and typically write deletion statements that need to scan the array anyway (@arr = grep {...} @arr), you don't see many linked lists in Perl.

      So you should think of a Perl list more like a C linked list.
      I think that's a very bad advice. It doesn't do justice to Perl arrays (nor lists), and Perl arrays/lists don't deliver the good features linked lists have.
        While I suspect that you were not responding to the most informed person in the world, I am willing to back up some of what he said.

        According to Code Complete 2, a number of studies have shown that, to a good approximation, the amount of code written per day in a programming language is independent of how high level that programming language is. Therefore you can estimate the productivity of people working in that language from the efficiency of saying things in that language. With that in mind he produces a chart of, based on real world code bases, the approximate relative number of statements needed in different languages to say the same thing.

        By his figures, Perl is 6 times as efficient to say things in as C, which is within the 5-10x estimate that Marshall gave. Incidentally by his figures, Java is 2.5x as efficient as C, which would make Perl over twice as efficient to code in as Java.

        About linked lists, one of the most common use cases for linked lists in C is that someone wants a queue or a stack which can grow arbitrarily without having to know the size first. For that use case, Perl arrays are a great replacement. For the case where you wish to insert or delete in the middle of an array, it is true that a linked list written in Perl scales better than using splice. But the overhead of Perl is so much that if your arrays only have hundreds of elements in it, the simple splice solution is more efficient than writing a linked list. (There is even more overhead if you want to keep your double-linked lists from leaking memory.)

        So while Perl arrays are theoretically not replacements for linked lists, for a great many practical purposes they are.

        The Perl coding efficiency is obvious. If you think that it is only like 2-3x, fine with me. From the code that I've written in Perl, I figure that it is more than that. But I would agree with a >= 2x number. So done point! The difference is so enormous I won't squabble about a minor factor of 2x.

        No, I didn't mean Perl array. I meant Perl list. Please explain what you think the difference is between a Perl array and a Perl List. I think this just some kind of nomenclature difference.. Not any real disagreement!

        Maintenance of a Perl "list" is expensive CPU wise and I didn't say that it wasn't.

        @arr = grep {...} @arr is essentially a scan of of what would be in C linked list, but as I said, even more powerful from a language standpoint.

        Update: I am still not "getting it". A simple Perl list is similar to a C char ** array (array of pointers of pointers to strings), but more flexible and more powerful.

      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 ...)

        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 ;-)

Re: Perl vs C
by ELISHEVA (Prior) on Mar 14, 2009 at 20:49 UTC

    In Perl it is easier to share code between code-bases. C's verbosity and macro support tends to encourage the development of large complex bodies of macros. Code can't be compiled without the header file defining the macros, and more importantly, the C code often makes no sense unless you are an initiate in that code-base's macro "jargon".

    Perl also lets one define language constructs and change the compilation process in seemingly hidden ways, but there is less incentive to use these tricks because Perl is a reasonably succinct language to begin with. Furthermore, doing this kind of magic requires some fairly advanced knowledge of Perl (e.g. understanding symbol tables or the difference between BEGIN and CHECK blocks and the contexts in which they are evaluated). As a result, customized "extensions" to the Perl language tend to be fewer, more well thought out, and better documented than your average C macro header file. (ok, I can see some disagreeing here :-) -- Perl has its own share of horrible code)

    Compilation and execution are integrated in Perl whereas C is normally compiled in one phase and executed in another. This makes Perl an ideal tool for solutions where (a) things might need to be patched on the spot (b) bootstrap sequences where tool A1 generates code for tool A2 which then automates the build of tools B1,B2,B3.

    In truth any scripting language could play this role. However, I find Perl is a particularly good scripting language choice because it cleanly supports a wide variety of data structures and its support for OOP allows close integration of data and action. When strictures are turned on it also does a reasonably good job of identifying misnamed variables and code that might not behave as intended. This makes it possible for one to maintain even complex scripted solutions with relative ease.

    Best, beth

Re: Perl vs C
by repellent (Priest) on Mar 15, 2009 at 03:37 UTC
      Which other time is more precious?
      Ask yourself that the next time you're waiting for an application to finish or a webpage to load.
          Ask yourself that the next time you're waiting for an application to finish or a webpage to load.

        Right. Selfish me is more preoccupied with getting my job done quickly to get to other important things in life.

        Update: Clarification: more development time saved allows even more tests to be written, profiling done, etc. which lead to better code quality in the long run. Considering runtime optimizations to be top priority above devel/maintenance time is detrimental.
Re: Perl vs C
by vinoth.ree (Monsignor) on Mar 14, 2009 at 05:54 UTC

    Dear Santhosh_89

    Have a look on this they have discussed increment operator precedence between C and Perl


      Actually if you read that thread you will discover that it discusses a single issue and that the issue is one of specific compiler/interpreter implementation unrelated related to language differences.

      True laziness is hard work
      I looked at this other post. re: C
      k = i++ + i++;
      That is "weird looking". I recommend a more clear statement of intent!
      x = i++; /*maybe*/
      k = x + x; /*maybe ???? */
      I am not sure what the precedence rules are with 3 +++ in row. I recommend that you use a couple of statements to make this more clear.

      BTW: In Perl, sub x (--$i, $i++) behavior is also undefined.
      The order of operands to a sub can be evaluated in any order. This is true in C also.

        In Perl, sub x (--$i, $i++) behavior is also undefined

        Not really. On all platforms, operands are always evaluated from left to right except for assignment operators, where it's right to left. People regularly rely on this.

        sub foo { shift->bar('foo', @_)) }
        { my $x = $x; ... }

        The latter is even documented.

        The problem is that it gets really tricky when lvalues are involved.

        f($i, --$i, $i);
        The first argument is evaluated first, but it's still affected by the decrement because Perl passes by reference.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://750575]
Approved by GrandFather
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (6)
As of 2017-01-21 11:24 GMT
Find Nodes?
    Voting Booth?
    Do you watch meteor showers?

    Results (184 votes). Check out past polls.