Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Perl vs. Python: Looking at the Code

by mothra (Hermit)
on Apr 03, 2002 at 15:44 UTC ( #156333=perlmeditation: print w/ replies, xml ) Need Help??

X vs. Y is a common direction that many threads take, in many discussion forums, on many radio stations, in many news broadcasts, and in many political arenas.

This post is another X vs. Y. However, unlike the majority of X vs. Y -- heck, let's even start getting more specific and say Perl vs. Python -- debates, this thread will attempt to measure the differences between these two languages by looking at differences on the coding level. Rather than just "well, it's just easier to do task XYZ in Python/Perl" I intend to do a bit of character-by-character analysis (I think you'll see what I mean) to show you why lately I've taken great interest in Python.

In fact, I'm even yearning to understand why Perl still manages to exceed the popularity of Python.

If you think this is a flame against Perl though, you've drastically missed my point. I'm here to present, from a coding standpoint, why I've come to see Python as an extremely cool language...for me, more useful than Perl I believe, and from there, to be shown -- by you, the viewer -- the contrary to my viewpoint.

Allow me to begin:

  • Variable access -- Perl guarantees that for virtually every time you access a variable, you will have to type at least one more character (and hit Shift!) than Python. And, when use strict (aka, good coding practices) is in effect, at least three extra characters to declare them (spaces are characters too :).
    PerlPython
    @foofoo
    my $foo = 1;foo = 1
  • Perl makes you type {}'s around your blocks and ()'s around your conditionals, which leads to a.) yet more typing, b.) annoying inconsistencies in styles (which doesn't seem like a big deal...until you're the maintenance programmer).
    PerlPython
    if ($foo) {
        print "hello world";
    }
    if foo:
        print "hello, world"
    if ($foo)
    {
        print "hello, world";
    }
    if foo:
        print "hello, world"
    Python's conditional constructs always look the same, which, when you're the maintenance programmer, is a welcome surprise. They also take up fewer lines.

  • Perl guarantees that you'll type at least one extra character at the end of every line. The ";", of course.

  • The Perl Way of function/method parameters (AND setting parameter defaults) takes more keystrokes, is harder to document, and less intuitive (because it's completely different to almost every other language out there, and you actually have to look into the implementation of the function or method to see what the parameters are!):
    PerlPython
    sub foo {
        my $arg1 = shift;
        my @rest_of_args = @_;
        ...do stuff...
    }
    def foo (arg1, rest_of_args):
        ...do stuff...
    sub foo {
        my $arg1 = shift || 0;
        ...do stuff...
    }
    def foo (arg1 = 0):
        ...do stuff...
    Python's syntax above is not only much simpler (i.e. the function definition syntax of having a function name followed by a parameter list in parenthesis, which is common to many languages), but, because it is part of the function definition itself, it's easy to write programs that automatically generate documentation. In combination with Python's "docstrings" (a string literal placed right after the definition of the function, that python's interpreter parses and puts into the variable func_name.__doc__) automatically generating module documentation is easy, without needing to know any freaky perldoc tags. And for lazy programmers, it's nice to save on the keystrokes too.

  • Perl makes you type more to access object properties.
    PerlPython
    $foo->bar();foo.bar()
    In combination with the added typing associated with variable access in Perl, this adds up.

  • Python has multiple implementations. Stackless Python (for smart people, that know how to use it :) and Jython which not only gives you access to virtually any Java class you might want to use, but -- because it's written in pure Java -- allows you to run Python on any Java platform.

  • There are huge chunks of perldoc sections that would make for completely irrelevant sections in Python documentation.
    perlreftut and
    perlref -- In Python, everything already is a reference. There's no need to learn the tricks of using them.
    perlvar -- Python's "special variables" are virtually self-documenting. e.g. func_name.__doc__
    perlboot and
    perltoot and
    perltootC -- Save for perhaps a little blurb thta might equate to a "pythontootC", Python's OO is as obvious as it gets. Want to declare class Foo that inherits from classes Bar and Baz? class Foo(Bar, Baz)...how much easier to you want it? :)
    perlpod -- docstrings are the only really "special" thing you need to know about documenting your Python code. However, there's nothing "special" about them. You write --> "this function does that" instead of --> # this function does that.
    perllol -- because everything in Python already is a reference, lists of lists work the way you think they would. [1, 2, 3] becoming an LoL would simply be (as an example) [1, ['foo', 'bar'], 3]. What other syntax would you have expected? :)
    The point being, fewer rules to learn == fewer rules to keep in your head.
Now...all of the above issues are what I would consider agnostic in religious flame wars. They show specific examples of how Python let's you type fewer characters, and/or do things in a cleaner syntax and/or in ways that lend to automating away tasks like creating HTML or PDF documentation of your code without having to know any special syntax to do it. On the religious side, many people reject Python because it uses indentation levels to group statements. With respect to Perl programmers, there are two serious flaws in this argument:
  1. It amounts to the same argument that non-Perl programmers use in saying "Perl sucks because it looks like line noise". You'll note in my illustration of why I seem to prefer Python these days, I've not used such an argument.

  2. If you wrote a simple parser to remove all the {}'s from Perl code blocks, you'd notice that Perl's code blocks would look EXACTLY the way Python code looks, because indenting code is a requirement of good coding practice.
So, there you have it. An empirical (yes, I've come up with these points from actually having used Python to do everything from script my IRC client, to writing a weather reporting module, to producing an online drugstore for a client) essay on why I think Python seems to win on most counts when measured against Perl. And before you suggest that it seems most points made seem to just say "you type less in Python" a.) carefully reread them because there's definitely more to it than that, and b.) ask yourself...even IF the languages were equal on every other count except that one allowed you to type fewer characters to get your job done, wouldn't you prefer the route of less typing? :)

Please show me a contrary, and equally backed up, viewpoint on this debate. For reasons already cited "it sucks because it uses whitespace to group statements" or "Perl is better because it has default variables" don't fly. That's 100% pure opinion. The points I've shown above are concrete examples of why, even with best coding practices, character for character, and due to language design issues you will save characters in Python, and also shows specifically why it's easy to write tools to autogenerate Python module documentation without knowing any special documentation syntax.

Warning: If you say something about Perl vs. Python in clear ignorance of, and obviously rarely having used, Python, You Will Be Flamed.

Heh.

Comment on Perl vs. Python: Looking at the Code
Select or Download Code
(jeffa) Re: Perl vs. Python: Looking at the Code
by jeffa (Chancellor) on Apr 03, 2002 at 16:03 UTC
    Your argument is at best trivial. Simply comparing the syntaxes of two languages is not enough for me to consider switching. I am sitting in on a Python class and so far i haven't seen a need for it in my queue. I'd rather spend my energy learning Perl6.

    Yes, you may be saving a character or two now, but wait until you need the full power of CPAN (and yes, this comment will self-explode when/if the Python 'CPAN' finally catches up to Perl's).

    jeffa

    Python: it's just like Perl - but different!

    UPDATE:

    quote the mothra in the Chatterbox:
    "realize that CPAN is just a really big collection of code that has all the same drawbacks as mentioned in the post."

    i don't need to comment on this, do i? ;)

Re: Perl vs. Python: Looking at the Code
by derby (Abbot) on Apr 03, 2002 at 16:05 UTC
    mothra,

    To sum up your arguments: python lets you type less. Not to convincing. You don't like braces for blocking, I don't like white space for blocking. Syntactic sugar - Viva la differance.

    -derby

Variable access counterpoint
by Fletch (Chancellor) on Apr 03, 2002 at 16:05 UTC

    Without reading the entire chunk of code, you can't tell what type of value a variable's holding. foo could be a simple integer value. It could be a list. It could be a dictionary.

    @foo is always an array. %foo is always a hash.

    Pay no attention to those perl scalars containing references to objects hiding behind the curtain . . . :)

    Not that Python doesn't have it's nice points (xmlrpclib for example), but it has warts of its own too (trailing commas can be syntactically significant, lambda's aren't really lambda expressions (i.e. closures)).

Re: Perl vs. Python: Looking at the Code
by mrbbking (Hermit) on Apr 03, 2002 at 16:09 UTC
    Ooh, flaimbait. Yum.

    For reasons already cited "it sucks because it uses whitespace to group statements" or "Perl is better because it has default variables" don't fly.That's 100% pure opinion.

    Everything you list as why Python is better than Perl is '100% pure opinion.' Nothing there is objectively 'better' than anything else. 'Better' is (almost)? always a matter of opinion. What is 'good' depends on one's values and one's goals.

    The points I've shown above are concrete examples of why, even with best coding practices, character for character, and due to language design issues you will save characters in Python, and also shows specifically why it's easy to write tools to autogenerate Python module documentation without knowing any special documentation syntax.
    OK - so your argument is that 'Python requires fewer characters and is easier to document.'

    Here's where I have to stop. I am in clear ignorance of Python, never (not rarely) having used it.

Re: Perl vs. Python: Looking at the Code
by bluto (Curate) on Apr 03, 2002 at 16:39 UTC
    I use Perl for two basic reasons.

    It is an extrememly rich language (TMTOWTDI). I can express what I want to in a way that pleases me (or my boss) most, depending on what I want.

    It has reached critical mass. I have a wide choice of existing solutions (i.e. CPAN), and I know it is supported well.

    I've looked at Python, but never used it. It appears to meet my criteria above -- it would take a lot of my time to find out. Perhaps if I didn't know Perl now I would spend more time trying. The main reason I don't is probably the same as why 99% of everyone else doesn't switch -- the arguments that I've seen put forth for it don't outweigh the pain that must be endured to convert over to it.

    BTW, why should I use Python when I can switch to Ruby? I've heard claims that its better than Perl and Python put together. There are many, many cases where arguments can be made for a less popular technologies (Apple ][ vs Commodore 64; C vs Pascal/Modula/Oberon/etc; Mac vs PC) and I picked the side of the less popular solution because I just thought it was "cleaner". Give me something that is *better* than CPAN and I might take a second look.

    bluto

Re: Perl vs. Python: Looking at the Code
by jepri (Parson) on Apr 03, 2002 at 16:51 UTC
    Jepri climbs into his asbestos suit. It really looks like princepawn posting under a different name. Ho hum, flame away...

    I just spent 4 hours trying to teach someone Eiffel, which is a B&D language par excellence. Interestingly enough, you could replace 'Python' with 'Eiffel' in your post, and you would have similar arguments like:

    No sigils for variable access - brilliant. Now beginners can't tell the difference between a scalar, an array and a function. And then they can't tell if they will be interpolated in a string. Sigils on variables indicate what they will do when the code runs. Declarations 3 pages away aren't very helpful. Ditto C, Pascal and every other damned language without sigils, including Python.

    No delimiting of blocks with () or {} signs - so you have to look at what isn't there to tell where the block starts and ends. In any conditional more complex than  x < 10 , you are probably going to use brackets to override precedence, or simply because you can't remember which operator wins. So beginners ask, why do you need brackets sometimes and not other times... Again, teaching beginners is more difficult, because there are less clues as to what is a statement and what is an expression.

    The perl way of taking arguments is pathological. Point to you.

    Object accessors - I just spent four hours with someone who kept typing io.put.integer rather than io.put_integer Operators that look like punctuation suck.

    Multiple implementations of the same language - so now, not only do you have to keep track of different hardware platforms, you have to be aware of how each implementation works on each platform.

    Update: I guess the point I didn't make explicit before is that if I can replace 'Python' with 'Eiffel' or any other word, or 'Perl' with 'C++' or 'Ada' or whatever then we aren't argueming languages, we're arguing language design features, independent of the languages that use them.

    This is a sizeable area of research, and thankfully the researchers are beyond pointing at their favourite language and saying "Look! Whitespace!". I will be interested to see how well perl6 incorporates academic theories into a current programming language.

    ____________________
    Jeremy
    I didn't believe in evil until I dated it.

Re: Perl vs. Python: Looking at the Code
by mirod (Canon) on Apr 03, 2002 at 16:56 UTC

    OK, so I don't know much about Python, and I --'ed you.

    Why?

    Because after reading your post I don't know anything more about Python than before reading it, except that some of its zealots (that would be you) are even more biased and short-sighted than Perl's.

    Most of your arguments are purely a matter of personal preference, nothing objective there, but I really liked the fact that you prefer Python because it lets you type way less characters than Perl. Kewl! So what's with constructs like string.replace, fo.readline() or sys.stdout.write? Shorter than Perl's tr, <> or print? I did not think so either.

    People like Perl or Python (or Ruby or Lisp or Smalltalk or whatever) based on how well the language suits them, rarely for "objective" reasons. I like the fact that Perl is complex for example, it keeps me interested, while C bores the hell out of me. If you prefer a simpler language, then by all means, stick with Python. I don't have a problem with it. I would even be happy if you could just go and post on PythonNunns or whatever the Python community site might be called.

    Just please don't troll here, thank you.

    Update: point taken, as noticed by mothra below, there is indeed a print statement in Python (how not object oriented BTW ;--). My bad. I guess my post makes no sense and I should give up Perl and find The True Snake Way then ;--).

      The moment you thought that sys.stdout.write was to Python as print is to Perl is the moment I stop reading your post.

      Too many people are responding, yet couldn't write a 50 line Python program to save their life.

      I'm done with this thread.

        mothra, honestly, what did you expect? Posting a pro-Python screed in a pro-Perl community, then stomping off to sulk when the responses you get don't meet your expectations of Python background knowledge is like whacking a wasp nest with a baseball bat, then complaining when you get stung.

        And if you're going to give Python plusses for the bits of its syntax that are terser than Perl's, you might want to consider Perl constructs that are terser than Python's equivalents. I have no first-hand experience with Python, so I can't really comment, but I'm told that regex matching and interpolating variables into strings are much more cumbersome in Python than in Perl. More propaganda?

        --
        :wq

        <block> The moment you thought that sys.stdout.write was to Python as print is to Perl is the moment I stop reading your post. </block>

        I think you're being unnecessarily antagonistic here. You did not address the underlying point of the parent node -- that you had ignored several of Perl's more concise features and focussed only on relatively minor syntax differences. Examples of concise syntax in Perl extend well beyond the list given above. In fact, I repeatedly see claims from Python users that Python is easier to maintain because Perl is too concise! Maybe this isn't true, but you didn't do much to disprove it with your response.

        You could at least have explained why his examples were wrong. (At least for the print example. I'm guessing that the other examples are legitimate since you didn't mock them.)

        But instead of a reasonable response, you were simply rude. You'll get a much more open discussion about this issue if you can address a dissenting opinion rationally. (And in fact you were quite helpful and courteous in your reply to my personal /msg on this subject.) That's my I downvoted this node, but only this one.

        Slightly offtopic: I found it very odd that you couldn't force yourself to finish reading a fairly short reply to your questions, but you could inflict an enormous top-level node on all of us without the benefit of a READMORE tag...

        buckaduck

Re: Perl vs. Python: Looking at the Code
by thraxil (Prior) on Apr 03, 2002 at 17:15 UTC

    i have to agree with the other posts that the terseness of some of the syntax is a pretty poor way to compare two languages.

    especially when all the examples are chosen with a bias. let's look at some other aspects of the syntax:

    #perl $foo .= $bar;
    #python foo.append(bar);
    # perl $foo =~ s/\W//g;
    #python import re foo = re.sub(foo,'\W','')

    my point is that with contrived examples, you can probably argue it any way you want. with perl's flexibility i've found that i can write overall shorter programs in perl than in python even if some of the individual statements are longer.

    if all you care about is terse syntax, you'll love colorForth: here's an IDE driver written in one page of code.

    anders pearson

      Another example of ignorance.

      Perl's "." operator and Pythons .append() list method, are two entirely different things.

      You've also managed to miss (like many), for primary points of the examples I cited:

      a.) clearer, more concise syntax
      b.) a shorter path to producing autogenerating documentation
      c.) having to only worry about, maybe, 4-5 different styles to maintain vs. 20
      d.) far fewer rules to remember
      

      I did say I was done with this thread, but I refuse to leave ignorance unchecked.

      I wrote this thread, hoping for concrete examples to the contrary of what I've said, and all I've ended up with is general "cuz I like it better" comments made by people who know almost nothing about Python.

        ...all I've ended up with is general "cuz I like it better" comments made by people who know almost nothing about Python.

        Well I refrained from detailed comment because you specifically said that you weren't interested in hearing from people who didn't know Python well. But it sounds like people who don't know Python well are about all we've got around here :)

        I've thought a few times that I really should make the effort to learn Python. I've bought the Learning Python book. I've sat down with it both in a comfortable chair and in front of a computer. I've learned many programming languages in my time. It doesn't take me long to pick up the differences in syntax.

        But learning Perl was different. When I learned Perl there was something about it that really made sense to me. It fitted my thought patterns far better than any other language I'd learned before. For ages after discovering Perl I didn't bother to learn an new languages because I could do what I wanted in Perl far faster than I could do it in any other language.

        In the last year I've tried to look at both Python and Java. Neither of them made the same impression that Perl did. They both seemed far too restrictive about how you did things. You seem to think that's a good thing in Python. I far prefer being able to do things in a number of different ways and being able to choose the best one for any particular job. I don't think that's a problem for any decent maintenance programmer.

        So, OK, you've shown that in a few cases you type less characters in Python. So what? Like others have said, the sigils mean something in Perl. Looks to me like you'd have to go searching for that kind of information in a Python program.

        I'll probably go back to learning Python and Java soon. I'll probably be able to get pretty good at them. But from what I've seen so far, I really can't see them replacing Perl as the language that I feel most comfortable with.

        --
        <http://www.dave.org.uk>

        "The first rule of Perl club is you do not talk about Perl club."
        -- Chip Salzenberg

        Another example of ignorance. Perl's "." operator and Pythons .append() list method, are two entirely different things.

        A good point (although rudely expressed). (mothra informs me that Python uses foo + bar as the equivalent of the dot operator.) But of course, push is still shorter than .append(). And none of this should have a major impact on which language is preferable.

        buckaduck

        Your honor the jury rules on the following counts.
        clearer, more concise syntax
        Charges not proved. Clearer != more concise sysntax. As has been mentioned many times with regard to sigils, a core perl design object was that different types of things should look different so as to reduce confusion
        a shorter path to producing autogenerating documentation
        Not proved. I wrote a simple but effective tool to add pod to an arbitray module class and it only took me an hour. But thats cause I used one of the most sophisticated regex engines there is: Perl.
        having to only worry about, maybe, 4-5 different styles to maintain vs. 20
        Not proved your honor. Complaints like this are redundant in the face of autoindenters like Emacs and PerlTidy. Does Python have a tidier?
        far fewer rules to remember
        Irrelevant. Try doing complicated things with simple tools and the result is convoluted.

        Yves / DeMerphq
        ---
        Writing a good benchmark isnt as easy as it might look.

      one other thing that comes in my mind AFAIK python has several RE modules (as do much of the other languages)... and guees how they call them :
      "Perl compatible regex"
      :") so if i look only one side i.e the RegEx side of view, 'cause the poster does exactly this ...
      ps. the bad thing is that from after a year or so they will say "Perl5 compatible regex", 'cause perl6-compatible-regex they will not have in the near 5years atleast :")
Re: Perl vs. Python: Looking at the Code
by Maestro_007 (Hermit) on Apr 03, 2002 at 17:29 UTC
    I'm currently working in an office full of Perl junkies who have to use Python (actually Jython) because of the reasons you cited. It was a bit painful at first, but the language is fairly well documented and easy to learn.

    One problem I have with it is the lack of CPAN. I think there's no underestimating its value. We are constantly running around trying to get modules or write our own. Python (especially Jython) hasn't reached the state yet where you can do just about anything, so frankly it's a pain to use.

    Is the syntax cleaner? I have no idea. When I was learning Perl the sigils were only a little confusing. Now they come naturally, so I don't know. It just seems to me like grammatical inflection, no less natural than conjugating verbs. Initially with Perl you spend lots of time getting used to it. In Python, there's no up front cost, but a constant cost when you have to look up the first use (notice I didn't say declaration... there isn't a use strict mode that makes you declare them) of any variable you see.

    The biggest problem I have with Python, though, is the attitude it has against messy syntax. I know that may seem weird, but I like the fact that have multiple options for doing the same thing. In talking to our more Python-oriented guys, that seems to directly offend them. To me, computer languages should be an attempt to map to human problems. Larry's 3rd State of the Onion was all about this concept. Trying to clean up the language to mask it may not be the most effecient use of our time.

    On the other hand, take a look at the 1996 article Perl vs. Python by Tom Christiansen. It's a bit out-dated, but it makes good points. The most salient for my company's application (besides Java compatibility) being its intrinsic object-orientedness. Perl's object model is powerful and allows many good things, but it's not as easy to learn as Python's. You have to be very good at Perl to be able to use Perl objects. You can use objects in Python within 24 hours of starting to learn it.

    All in all I miss Perl terribly and still use it in my personal projects, but so far Python isn't stealing my sheep, robbing my house, or giving me shooting pains up and down my spine, so we'll keep using it. It's certainly better than that Barbarian horde we tried to hire to work on this part of the application (sorry, inside joke).

    MM

    p.s. Want a laugh? Try to imagine a Python Golf Challenge!

    Update: I knew I had a specific example of "cool" Python syntax that I did want to share:

    if listElement in aList: ... do stuff ...

    In Perl you gotta do this with grep (or something else like that). It's pretty.

    And another thing, this book saved our lives on this project. It's very objective, doesn't get at all religious, and has a very informative feel to it. "If you want to do this in Perl, here it is in Python." It has an alphabetical list of functions and their equivalents. I can't recommend it higher. It does not seek to answer "which is better", it just recognizes that this problem exists and shows how to cope.

      if listElement in aList: ... do stuff ...
      In Perl you gotta do this with grep (or something else like that).

      Although we can apparently look forward to the following constructs in Perl 6 (if I read this correctly):

      # Do stuff if $list_element is in @a_list if ($list_element =~ @a_list) { ... do stuff ... } # ... OR ... # Loop through a bunch of list elements foreach @list_elements { # Do stuff if the current element is in @a_list when @a_list { ... do stuff ... } # If not in @a_list, what about @other_list ? when @other_list { ... do stuff ... } }

      buckaduck

      Is a language that encourages cute ways to state bad algorithms better or worse?

      The syntax is pretty. But in some ways it is nicer that Perl encourages you to think about whether there is a more scalable way to do it. (Use a hash!) And if you want the idiom, it is easy enough to create in Perl.

Re: Perl vs. Python: Looking at the Code
by cjf (Parson) on Apr 03, 2002 at 18:10 UTC

    My entire experience using python consists of reading a few online tutorials and writing a couple "Hello, World!" level scripts. In compliance with your warning, I will not comment on the technical aspects of Perl vs Python (feel free to flame me anyways though :)

    What I will comment on is the style in which you asked this question.

    First of all, your post focused purely on why Python was better than Perl. Your bias was very obvious from the beginning and you failed to mention any area where Perl had an advantage. A good argument will show the strengths and weaknesses of both sides, not the strengths of one and the weaknesses of another.

    Secondly, your argument focused mostly on very minor syntax differences. Saving keystrokes is not a huge issue. If you truly feel that Python is a superior language you should have at the very least written more about how you believe it scales better for larger products, given more in-depth examples of how development time is faster, and provided some benchmarks.

    Thirdly, the language in your post was very argumentative. Read the last three paragraphs of your post again. They have a very condescending tone, insult the intelligence of the reader, and to top it all off you end them with You Will Be Flamed. This doesn't exactly provide the best environment for a reasonable discussion.

    I alway look for the best tool for the job and enjoy reading comparisons between languages, However, your post has taught me nothing about Python that I didn't already know. I encourage you to take these points into consideration and post a more educational node in the future.

Re: Perl vs. Python: Looking at the Code
by MungeMeister (Scribe) on Apr 03, 2002 at 19:45 UTC
    Well, I have to say I ++'d your original post for starting a discussion comparing the 2 languages, but I've --'d most of your responses to other posts for acting like an ass instead of fostering any kind of real debate. What did you expect? The people here know and love Perl and probably don't know Python. That really limits the discussion.

    That being said, the discussion in most ways, boils down to what I like. What works best for me. If there was an absolute best language, then there would be only one.

    Personally, I like the character to denote scalar, array, hash. I like that a scalar can have the same name as an array if I want. I like that I'm not forced into OO when I want to write a one time program that doesn't need it. I like that there is more than one way to do it. If you don't like that, great! Go ahead and use Python. Isn't it great, you have a choice!

    Now, quit behaving badly because people don't like your opinion, which is all you've stated. They are stating their opinion.

    If you want similar fun, why don't you take a trip to Canada and start a debate about which language is better, French or English....

    MungeMeister
      Well, I have to say I ++'d your original post for starting a discussion comparing the 2 languages, but I've --'d most of your responses to other posts for acting like an ass instead of fostering any kind of real debate. What did you expect? The people here know and love Perl and probably don't know Python. That really limits the discussion.

      You're more than welcome to explain to me how this justifies their making "points" based on Python fallacies.

      Take mirod, for example, who learned after making his reply that Python has a print statement.

      How would you feel if someone flamed your liking for Perl, and turned around and said something like "Oh, Perl has scalars?"

      Have I been rude? Yes, in direct accordance with that which I stated in the OP. Points made from total ignorance and lack of experience with Python would be flamed.

      They have been, they will continue to be. I was hoping to get responses from those who were reasonably well-versed in both languages, and have gotten directly the opposite.

        I believe that it was the great Charles Schultz who said that every now and then a person needs to be held and told Poor Sweet Baby, so in the spirit of Monkly Love and Fellowship: There, there... poor sweet baby.
        ()-()
         \"/
          `                                                   ` 
        
        I never said you weren't right...

        The point that mirod was making was that Python is more succinct is areas, and Perl is more succinct in others. So he picked a bad example, and uninformed example, so what? You've never made a mistake? You attacked (yes, I used that on purpose) the language that this site supports. Of course people that don't know Python, but love Perl, will take the defensive.

        By the way, if I posted your exact message in a Python community with all of your arguments reversed, I bet I would be flamed, just like you got here.

        Dragging back an analogy, try going to France and telling them that their language is not as good as English because you have to put le, la, or les on the front of all the nouns. How stupid is that? Get a modern, real language. I'll send the body bag....

        MungeMeister
(smitz)Re: Perl vs. Python: Looking at the Code
by smitz (Chaplain) on Apr 03, 2002 at 20:27 UTC

    Some thoughts...


    • Variable Access

      Yeah, I need three extra keystrokes to declare a variable, and an extra one each time I access it. So? Like Fletch said, I can skim over someone elses code and know what type of a variable is being used.
      What does this mean: @{ $scalar }? I can tell straight away, thanks @ and $ symbols.


    • Block delimiters

      Inconsistencies in styles? There are but two (block styles). And I like seeing where blocks stop, dont you? Im sure I could get used to whitespace, but it seems somwhat counter-intuitive.


    • A ; at the end of each line

      Python requires a newline. Ok, its a bigger key, you win.




    1. I've come to see Python as an extremely cool language...for me, more useful than Perl
      yet your comparison boils down to less typing. Fair point, kind of, but that doesn't make something more useful.

    2. I think Python seems to win on most counts when measured against Perl.
      I still dont see how youv'e measured either of the languages except keystrokes and briefly touching on self-documentation. Does that sound dirty to anyone else?


    3. For reasons already cited "blah blah blah" or "yadda yadda yadda" don't fly. That's 100% pure opinion.
      Now Im really not here to stop on anyone's toes, but 90% of your post is opinion.
      To summarise my post, Can you repeat the question?
Re: Perl vs. Python: Looking at the Code
by Juerd (Abbot) on Apr 03, 2002 at 21:23 UTC
    Greek doesn't look like our texts, but what does that say about grammar or pronunciation? Is Greek harder because it uses other symbols?

    Even if Python were easier because of its curlyless syntax, does the dictated whitespace make it any easier? (Can editors find block begins/ends?)

    How about all the other features a modern language has. Do your scripts not use regexes? How is a standard object defined? How are errors usually handled (can you do an easy "or die")?

    Programming efficiency is a lot more than avoiding line noise. In business life, time really IS money.

    How about freely available ready-to-use modules? HTML parsers? XML parsers? Database drivers? Conversion tools? Inline::-alikes?

    (Syntactic) Sugar is nice, but you need vitamins to survive.
Re: Perl vs. Python: Looking at the Code
by atcroft (Monsignor) on Apr 03, 2002 at 21:36 UTC

    I quote...

    "If you think this is a flame against Perl though, you've drastically missed my point. I'm here to present, from a coding standpoint, why I've come to see Python as an extremely cool language...for me, more useful than Perl I believe, and from there, to be shown -- by you, the viewer -- the contrary to my viewpoint."
    and ...
    "Please show me a contrary, and equally backed up, viewpoint on this debate. For reasons already cited "it sucks because it uses whitespace to group statements" or "Perl is better because it has default variables" don't fly. That's 100% pure opinion. The points I've shown above are concrete examples of why, even with best coding practices, character for character, and due to language design issues you will save characters in Python, and also shows specifically why it's easy to write tools to autogenerate Python module documentation without knowing any special documentation syntax."

    Ladies and gentlemen, brothers and sisters, it strikes me that this was not an attempt to start a forest fire of sorts, but a plea for knowledge-a request for clear, logical, objective reasons and examples for one learning to continue to learn (besides the journey that is the learning itself).

    Can anyone post examples in both of the same functionality, comparing/contrasting them, for instance? Examples related to their internal formats, or processing time, or resource efficiency would also seem to be in order (and these are the kinds of things I hoped for when I saw the post).

    I believe that a wise man once said that when the only tool you have is a hammer, after a while all problems begin to look like nails. While I have considered trying to learn Python in addition to learning more of Perl, I must admit my lack of knowledge in Python (but then again, I consider myself still very much an "egg" in learning Perl); elsewise, I would try to offer some constructive comparison or example.

    I look forward to following this thread, and I pray that more information will be presented which will allow objective consideration of the issue, and allow us to expand our wisdom.

Re: Perl vs. Python: Looking at the Code
by danger (Priest) on Apr 03, 2002 at 22:41 UTC

    Hey mothra, I guess I know why you haven't been to the local Perl monger meetings in a while ... :-)

    Picking out individual bits of syntax as a basis for comparison is simply fraught with problems. All the more so when your comparison boils down to counting characters typed in each fragment. If you like Python better than Perl, that's fine, I think Python is a fine language too. If you think it is easier to learn, easier to maintain, and/or simply easier to think in, that's just fine too. But I cannot fathom choosing to base so much of your debate on a few tiny instances of being able to type a few less characters in one or the other.

    However, if you are really interested in make that a comparison issue, please do so with something other than isolated fragments. Anyone can play that game --- no one wins, and what's more, no one learns.

      Hey mothra, I guess I know why you haven't been to the local Perl monger meetings in a while ... :-)

      Well...not quite. :) I've been busy, planning on moving to Europe, trying to sell my car, etc. In January, I was in London and Amsterdam, and got together with a couple of the London.pm'ers.

      My motivations are much more to do with finding the tool that lets me be as lazy as possible.

      Now, quickly, on to the code (I have to actually do some work right away, heh).

      First off, I was hoping to say that Python's fileinput module (its input() method specifically) was equivalent to Perl's <>, however it isn't. I've sent a message to comp.lang.python to try and understand why they work differently, because I understood them to be the same, until I tried to map it onto the wc program.

      Anyways, to the code.

      First off, I ran your programs on my machine (Pentium 733, 256 MB RAM, cygwin, NT4WS, Python 2.2, Perl 5.6.1), and large.txt was an 11 M file.

      $ time ./wc.py wc.pl wc.py large.txt 21 58 494 wc.pl 25 96 698 wc.py 382230 1290003 11930691 large.txt 382276 1290157 11931883 total real 0m7.922s user 0m7.218s sys 0m0.124s $ time ./wc.pl wc.pl wc.py large.txt 21 58 494 wc.pl 25 96 698 wc.py 382230 1290003 11930691 large.txt 382276 1290157 11931883 total real 0m4.484s user 0m4.186s sys 0m0.093s

      Then, I made some changes to the Python:

      #!/usr/bin/python import sys files = map(lambda f: open(f), sys.argv[1:]) or [sys.stdin] Twords = Tlines = Tchars = 0 for file in files: words = lines = chars = 0 for line in file.xreadlines(): lines += 1 words += len(line.split()) chars += len(line) print "%7d %7d %7d %s" % (lines, words, chars, file.name) Twords += words Tlines += lines Tchars += chars if len(sys.argv) > 2: print "%7d %7d %7d total" % (Tlines, Twords, Tchars)

      With the following results:

      $ time ./wc.py wc.pl wc.py large.txt 21 58 494 wc.pl 17 74 518 wc.py 382230 1290003 11930691 large.txt 382268 1290135 11931703 total real 0m6.157s user 0m6.046s sys 0m0.124s
      It seems you were using a fairly old version of Python. Version 2.1 sped up line-by-line file access.

      So, for what point? I'm not sure, but you said you were interested in seeing a better (though I'd definitely not dare claim "best") version of the Python code, so there's my contribution. :) Also, it's worth noting that the speed differences in the example are neglible.

      Update I: words = lines = chars = 0 might be slightly more idiomatic. I also would have written the map code (in the Python version) all on one line. That's a style difference, I guess. :)

      Update II: Okay, I put the changes in the Python code mentioned in Update I.

      Update III: And, for those who claim Python "forces" you into its own coding style, note that I could have written the map code using a list comprehension instead:

      files = [open(f) for f in sys.argv[1:]] or [sys.stdin]

      Python gives you more than one way to do it. IMHO it "takes away your options" in places where too many options are a Bad Thing anyway. (e.g. one way to define func parameters instead of using shift or @_ in Perl), totally eliminating any concerns about differences in {} style, because they're gone, etc.)

        Thanks for the code followup --- I do like the list method you showed rather than my lambda hack (like I said, it's been sometime since I actually played with Python ... something around 1.5.x, it didn't even have += back then iirc). You are right, Python has certainly improved in speed: From 31 to 13 secs just switching to 2.2.1c2 vs 2.0.1, and then to 11 secs using xreadlines(). Cheating and reading in whole files into memory and then working with them brought it down to 8 secs --- but the same cheats on the Perl version took it from 7 to 3 secs. The better relative improvement in the perl cheat is because we can get a "word" count via s/\s+//g without building a list (after, of course, we get the newline and byte counts), I couldn't find a way to do that in Python without building a list --- so the len(string.split()) was the best I could do in Python). Also, I did get a python version working with fileinput, but it was vastly slower and has awkward semantics for dealing with individual files while you iterate through them (ie, rather than an 'eof' test to see if you are at the end of the current file, you get a 'isfirstline()' test to see if you just read the first line of a new file ... this makes for awkward logic in my opinion).

        All said and done, although I'm not interested in relatively small differences in the number of characters --- one of your strong concluding statements in your original post was:

        The points I've shown above are concrete examples of why, even with best coding practices, character for character, and due to language design issues you will save characters in Python

        And I think, once you look at the context of actually writing programs, rather than syntax fragments, your statement won't really hold up. Although, perhaps now others may see that Python isn't necessarily as verbose as it is often made out to be. Your updated version looks quite nice :-)

        As for your comment that the circa 3:2 speed differential is negligible, I suggest that perhaps depends more on application domain and the kind of work you usually do. Further, the speed difference can be much more significant --- using regexen appears to be much slower in Python. Example: A simple grep script (takes a pattern, reads stdin, prints lines that match); using a pattern of "a.*e.*i.*o.*u" on my /usr/dict/words file (find all words containing the ordered (not necessarily contiguous) sequence of vowels). The Python version took 7.5 secs, the Perl version took 1 sec, and the C grep on my box took 0.2 secs --- incidentally, my words file is non-standard and contains 263,533 entries, of which 47 match the pattern given. For myself, this renders your 'if the languages were equal on every other count' qualifier somewhat moot.

        As for module documentation --- doc strings are nice for what they do, but rather limited. In fact, the primary documentation for Python and its libraries is a set of LaTeX files. Perl's POD isn't as flexible or as powerful as LaTeX, but it is simple and it is embeddable, which are pretty good properties, and provides a standard documentation model (and utilities) for all of Perl and its modules.

        Some of the other points you raised are valid: a standard language reference capabable of supporting mulitple implementations can be a good thing versus just a reference implementation; fewer rules and fewer styles can certainly help beginners (though can also be constraining to experienced programmers); Python's instrinsic OO model is simpler and cleaner; Argument passing in Python is nicer. However, Perl6 looks poised to address most of these, though I don't expect to see any kind of release before summer 2003. Something you didn't mention is that Python ships with a pretty sizeable library --- although CPAN remains unmatched in any language.

        Anyway, perhaps I'll see you at the next PM meeting and we can follow this up over a beer or three :-)


        >>> Python gives you more than one way to do it. IMHO it "takes away your options" in places where too many options are a Bad Thing anyway. (e.g. one way to define func parameters instead of using shift or @_ in Perl), totally eliminating any concerns about differences in {} style, because they're gone, etc.)
        >>>

        See you are missing it again the GOOD-THING as invented by python and/or perl designers may not be the good-thing for you... that is the main difference in Perl u take the responsibility to not screw the things in Python u do but not so much ... and the drawback of the python way is u loose the freedom of expressing yourself better...
        Again this may be is what u want and it is OK. But perl-ers don't like this they like freedom.
Re: Perl vs. Python: Looking at the Code
by Starky (Chaplain) on Apr 04, 2002 at 04:19 UTC
    All of this discussion about whether Perl or Python is better is like two identical twins calling each other ugly.

    I've only dabbled in Python, but enough to know both Perl and Python are fine languages.

    My preferences remain firmly with Perl because the syntax flows more naturally for me and there is just no substitute for the CPAN. I really enjoy being part of the Perl community as well, which is the most friendly and intellectually stimulating technical community I've ever seen :-)

    In my professional life, whenever a language choice has been considered with the possibilities being Perl and Python, almost invariably (unless Java integration were needed) Perl ends up simply being the most practical choice.

    While I look forward to more healthy debate, I hope the Perl and Python communities focus on complementing each other through efforts such as Parrot. Each will benefit more from supporting the other than by detracting because the qualities they have in common are the things that make each a strong language and technical community.

Re: Perl vs. Python: Looking at the Code
by ariels (Curate) on Apr 04, 2002 at 12:00 UTC

    Some good points here:

    Multiple implementations are good:
    Code should be written to a language spec, not to a particular implementation. Observe how clear ISO C is about "x=x++" (it is undefined behaviour). Perl isn't so clear; what's worse is that, since there's only one implementation, "suck it and see" might be considered a good answer (it isn't, but only because of the possibility of a later implementation changing).
    Function parameters
    The Perl way makes some nifty things possible, but it doesn't "make the easy things easy".
    Docstrings
    (Stolen shamelessly from Lisp, of course). Perl doesn't have an interactive mode (but see my RFC 184 for Perl6, which I hope will be approved), but even so docstrings would be nice. Not that PODs are bad...

    Some of the points are awful:

    Less typing with Python:

    No "concrete examples" to show this; a study of a short program implemented in both languages would go a long way to convince Perlers of this. Especially given that the claim is a bit odd -- most Pythoners I spoke to were enamoured of their language's verbosity, and said that made it better than Perl.

    But WHY is this a measure of language quality? Surely Perl wouldn't be a better language if we removed length, on the grounds that y///c is one keystroke less?

    Here's what put me off Python:

    No closures

    When people say Perl lacks closures, they mean you have trouble if you define a named sub inside a named sub (and try to return it). Python is much worse, though: it invents a new concept of "scope". You have "outer scope" (globals, really) and "inner scope" (dynamic variables, like local creates in Perl). You cannot write

    def adder(x): return lambda y: x+y a = adder(5) print a(3)
    because `x' is lost. The manual says to fudge it with default argument values, by drilling your variables down into the scope:
    def adder(x): return lambda y,a=x: a+y
    This is horrible! After a=adder(5), a(3) gives me 8, but so does a(4,4).

    Closures aren't some academic abstraction; for instance, they probably form the basis of the most readable, intuitive style for coding Perl/Tk (or any other GUI).

    Regexps
    What can I say? Perl does it better. I use regexps a lot; this "little language" is immensely powerful and intuitive.

    Surprisingly, most of Python's real advantages have been eliminated, too!

    Tuples
    Internals said to be "nicer"
    If you've ever tried to write any non-trivial XS (or Swig or Inline), you probably cursed Perl. My Pythoneer friends say Python internals are nicer, and better-documented.
    Nice mechanism for "obsoleted" and "proposed" language features.
Re: Perl vs. Python: Looking at the Code
by extremely (Priest) on Apr 04, 2002 at 22:57 UTC
    If you really spend more time and effort typing and formatting code rather than thinking, isn't this whole discussion moot? You aren't a programmer, you are a typesetter. =)

    If minimal typing and pretty layour really are your primary criteria then you can probably do better than Python, too.

    --
    $you = new YOU;
    honk() if $you->love(perl)

      LOL. Wish I could ++ this twice.

      -Lee

      "To be civilized is to deny one's nature."
mothra vs. Perl: Looking at the Past
by Anonymous Monk on Apr 05, 2002 at 08:53 UTC
    This is not a response to your post, but instead a response to your behaviour. If you practice things that are in clear contradiction of what you preach, You Will Be Called Out:
    • Re: What is it about perl that makes perl so cool? "Perl is nice to look at. It's quite unlike any other language out there and beautiful to read."
    • Re: Perl Resolutions "Avoid engaging in flame wars, especially language wars. The right tool for the right job!"
    • Re: Just a thought "There are at least 5-6 things that I HATE about any and every language I've ever used..."
    • Re: Re: Perl's warts "And just one more thing I can't help but comment on...use Python for large projects? eek...I started testing Python out by doing (or starting to do) a new client of mine's site with Python. I got severely turned off by the syntactic whitespace when a.) I indented one line with a tab and the next line with spaces and the compiler complained (a completely invisible error), and b.) I downloaded what I thought would be a reusable form mailer Python program, only to find out when I got it that the indentation was all messed up, rendering the code useless. I can't imagine how much my paranoia would increase if I was dealing with a 20,000 - 50,000 line Python code base."
    • Re: Re: Perl and Java "By the way ... but we can we waste slightly MORE time comparing language XYZ to Perl?"
    • Re: Re: Perl and Java "Views of 'this language sucks' or 'that OS sucks' are a dime a dozen. How many more dead horses need to be beaten?"
    • Re: Changing owner of files: Windows vs Linux (or Why I hate Windows) "dismissing the good points of any tool ... because you found something that sucked is a sign that you probably haven't taken the time to match the tool against the task or you're being overzealous."
    • IRC vs. Newsgroups vs. Web Forums "Has anyone else 'had it' with all the (flame|holy)wars going on?"
    • Re: Stubborn as a Saint "If you want to get a good idea of someone's technical ability follow their writings!"
    • Re: Choose the most powerful language "I've been shown a reason to change the way I think."
    • Re: Concurrency : FORK and knife "Consider lurking for a little while longer to see how things work around The Monastary before you post again."
    Take it easy man, you can't learn 10 years of good programming skills in 2.

      You've posted anonymously, so you don't count.

      But:

      1. I'm flattered (and a little bit freaked out) by the fact that you know more about me than I do.

      2. You should have read my OP a little closer. I'm not flaming Perl, but lately, the more I've learned about Python, the more it's seemed to have some advantages over Perl.

        Because you seemed to have missed two important remarks in my OP, I'll cite them yet again (despite the fact that they already have been cited).

        If you think this is a flame against Perl though, you've drastically missed my point. I'm here to present, from a coding standpoint, why I've come to see Python as an extremely cool language...for me, more useful than Perl I believe, and from there, to be shown -- by you, the viewer -- the contrary to my viewpoint.

        and:

        Please show me a contrary, and equally backed up, viewpoint on this debate.

      I haven't said anywhere in my post "Perl's nothing more than line noise, I'll never use this crap again". I've merely been learning more about another language (Python, you may have noticed), and found some things I think I may like better, and wanted to see the contrary to this viewpoint (as in...no...you might think these are better, but they aren't, because look at what Perl can do, etc.). Unfortunately, I got only few responses (and no, you're not in that list, to be sure) that were good examples of a contrary viewpoint, by showing some knowledge of both languages, and offering their comparisons based on that.

      Don't mistake contradiction with evolution.

        I've merely been learning more about another language (Python, you may have noticed), and found some things I think I may like better, and wanted to see the contrary to this viewpoint (as in...no...you might think these are better, but they aren't, because look at what Perl can do, etc.).

        But... But... But... You're asking us to form your opinion on perl.

        Python is just different. Better than perl at some tasks, worse than perl at other tasks, but mostly just a bit different, with different goals.

        If you like python, go code in python for a while, and come back with a good contrast on what you can really do better/easier in python, and what is really harder in python (vs. perl, of course). That would be something worth discussing.

Re: Perl vs. Python: Looking at the Code
by rje (Deacon) on Sep 01, 2005 at 19:09 UTC
    This is an old, old thread, but I feel like throwing in two cents, since I've recently been seeing how Python feels. And it feels strange. Not necessarily bad, just strange.

    First, it doesn't give you many hypotenuses. Don't get me wrong, there are some nice shorthands, to be sure -- the slice syntax is cool and could be borrowed -- and its object-orientation is politically correct and (more importantly) doesn't look bizarre. And its treatment of Strings as Lists is, in the long view, probably correct. However, I've seen no other syntax benefit so far over Perl, and in fact that pales in comparison the cool shortcuts that Perl gives for free. And the CPAN sweatshop, where you can Find It's Already Been Done For You.

    Moreover, there are some things that would be sorely missed if I had to use Python for some jobs. In particular, it feels too far removed from closures. This is purely a side-effect of not using explicit block delimiters, I suspect. The lack of Perl's concise range operator is painful to me. There's also a slight whiff of Java about when I code in Python. And any niceness in syntax is nullified by some very strange things which will, due to frequent usage, bother me all the time, such as the trailing comma on the print statement! What's the problem here? Why can't you use \n, or at least bow to Java and have print() vs println()?

    And, though I haven't delved deeply into it, variable interpolation in strings looks painful in Python. Isn't the C language 30 years old now?

    Next, there are a couple things I'm waiting for in Perl6. In particular, a more sensible way of declaring, creating, and handling objects and object methods. Python captured the essence of quiet object-orientation. And I'm all for the loose mixin-like behavior of Perl6 (and Ruby) too. And, already explicit is the ability to change Perl to what you want it to be via predeclaration. All is fair if you predeclare is my mantra. (You can even do that now in Perl5 with source filtering.) If I want to steal some hacks from Arc then I can predeclare them in my Perl modules. This is a big win.

    To sum up, basic Python is just a hybrid Perl-Java-LISP language which appears to bring little that is new. And while I love Perl, respect Java, and like LISP, and think emulating them to some degree is admirable and even worthwhile, I still get the feeling that I'd rather have the "value" (if that can be assessed) of Java and LISP without sacrificing Perl.

    I think it's time to put Python back on the shelf, and see what Ruby feels like.
      *delurk* This really isn't the place for anything vaguely indepth, but:

      There's also a slight whiff of Java about when I code in Python
      If your Python feels like Java you're probably not using it correctly - I suspect that you're using range() for indexing. If you're using range(len(foo)) use enumerate() instead. I also suspect you haven't been using generators, iterators, and listcomps as often as you should have been.

      In particular, it feels too far removed from closures.
      Hmm... Python has closures, just not anonymous ones (though because strings and numbers are immutable and one has to store variables in a mutable object (list or dict), classes - or in some cases generators - may be preferred).

      Regarding print, if you're using lots of prints terminating in commas, your code probably isn't very Pythonic...(trailing comma is likely to be removed in 3.0)

      Variable interpolation is as painful as C's (though you can use string.template for interpolation closer to Perl's)

      Anyway, have fun with Ruby ;-) *relurk*

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlmeditation [id://156333]
Approved by ariels
Front-paged by ariels
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (12)
As of 2014-08-28 14:17 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (262 votes), past polls