APLawrence.com -  Resources for Unix and Linux Systems, Bloggers and the self-employed
RSS Feeds RSS Feeds











(OLDER) <- More Stuff -> (NEWER) (NEWEST)
Printer Friendly Version
->
-> Python vs. Perl




Python vs. Perl

Perl folk seem not to like Python, at least not at first glance. It's easy to understand why: the languages serve similar purposes, but have annoyingly different syntax and structure. There have been converts, though, and Eric S. Raymond's experiences are probably not atypical.

I've noticed that Linux Journal has had more than a few Python articles, and the most recent issue has begun a tutorial series. That article prompted me to take a more serious look.

First Impressions

I went to http://www.python.org/doc/current/index.html and used the excellent tutorial there. I found things to like and things to dislike immediately:

Liked


  • That object methods are the default, not something tacked on:
    a=['abc','def','ghijkl']
    print "Before Append",a
    a.append('hello')
    print "After Append",a
    
    ...
    
    Before Append ['abc', 'def', 'ghijkl']
    After Append ['abc', 'def', 'ghijkl', 'hello']
    
    

    There's a whole boatload of built-in methods: see http://www.python.org/doc/current/tut/node7.html. I'm not going to say I like these better than the Perl functions that do similar things, but I certainly have no problems with these and can see good use for them.



  • That integer math is the default unless one or more of the operands isn't an integer:
    print 7 / 2
    print 7.0 / 2
    
    ...
    
    3
    3.5
     
    


  • That semicolons at the end of lines are optional: any of these are fine:
    print 7/2;print 7/2.0
    
    print 7/2;
    print 7/2.0
    
    print 7/2
    print 7/2.0
     
    

    Leaving off semicolons is a common Perl goof..



  • Indentation syntax. Everything indented is part of what happens when "mytest" is not 0 or null:
    mytest=1
    if mytest:
       print "mytest ",
       print "is set"
    
    print "hello ",
     
    

    Oddly, this is something most Perl types really hate, but I'd find it easy to get used to. Since most of us tend to indent code within blocks anyway, it seems reasonable to me to dispense with the braces and just use the indentation.



  • Default argument values for functions:
    def foo(prompt="huh?", count=2):
     print prompt,count
    
    foo()
    foo("go","seven")
    foo(count=89)
    
    ...
    huh? 2
    go seven
    huh? 89
     
    

    I really like that.



  • Exception handling. I like "try/except" logic (apparently Perl 6 has this too);



Disliked

  • Variables. I don't like the C-ish variable names. I LIKE that Perl requires a $, @ or whatever ahead of a variable name - it makes it stand out. I also like that Perl's $a is different than @a etc.

  • Data types. Setting a one value tuple is absolutely ugly:
    this='abc','def',0;
    print this, len(this)
    this='hello' # NOT a tuple
    print this, len(this)
    this='hello', # Now it is
    print this, len(this)
    
    ...
    ('abc', 'def', 0) 3
    hello 5
    ('hello',) 1
    
    

    This is a consequence of not having data prefixes or formal declarations.



  • No "a++" or "a--". Sheesh.

  • No "$_". There's _, which apparently isn't quite the same - unless I misunderstand, which is certainly possible at this point.



Overall, I think I'll stick with Perl. I can see Eric Raymond's argument for larger projects, but I don't do large projects anymore and I just find Perl's wild versatility and lack of insistence (More Than One Way To Do It) more attractive than more structured languages. But Python certain does have its appealing aspects, so I'll probably dabble with it here and there.

I certainly cannot agree with some who insist that Python is easier to read or understand than Perl. That's just ridiculous: neither of them add anything to helping understand someone else's code. Perl isn't any more "cryptic" than Python. Nor can I understand the attitude that Perl is deficient because you can do things in multiple ways. If you insist on such structure, enforce it upon yourself: nobody is stopping you. I do understand that for larger projects, with multiple people involved, structure is more necessary.

All in all, I wouldn't be terribly upset if I got "stuck" with something that had to be done in Python. It's a very reasonable scripting tool and does have some very nice features.




If this page was useful to you, please help others find it:  





11 comments




More Articles by - Find me on Google+



Click here to add your comments
- no registration needed!
"Overall, I think I'll stick with Perl. I can see Eric Raymond's argument for larger projects, but I don't do large projects anymore and I just find Perl's wild versatility and lack of insistence (More Than One Way To Do It) more attractive than more structured languages. But Python certain does have its appealing aspects, so I'll probably dabble with it here and there."

I tend to agree here. Perl just seems to be more flexible -- almost like BASIC in many ways, and if I'm trying a quick hack-together, I'd rather not have to deal with Python's pendantic tendencies.

"I certainly cannot agree with some who insist that Python is easier to read or understand than Perl. That's just ridiculous: neither of them add anything to helping understand someone else's code."

How true. Unless you really understand how someone else thinks, how are you going to truly surmise what was intended by looking at uncommented code? I look at some of my old, uncommented code (especially 65xx M/L) and *I* can't figure out what in blue blazes I was thinking.

"Nor can I understand the attitude that Perl is deficient because you can do things in multiple ways. If you insist on such structure, enforce it upon yourself: nobody is stopping you. I do understand that for larger projects, with multiple people involved, structure is more necessary."

For more structure, use C. <Smile>

My impression of some of these johnny-come-lately languages (e.g., Python) is that they were developed by folks who couldn't think in ways supported by other languages or simply don't like adhering to established practices. While the latter isn't necessarily a bad thing in computerdom, it also isn't always good. Just take a look at the Microsoft mess for an excellent example.

In any case, just how many languages does a bloke have to know to make a living? According to my wife, there's so much gobbledy-gook (her term for any programming language) in my head, any semblence of normal thinking disappeared years ago.

--BigDumbDinosaur





Mon May 30 12:23:16 2005: 591   anonymous


I'd like to read about the differences in object orinted programming features. Can Python/Perl do the same things Java does (encapsulation, polymorphism etc.)? I know not natively, but with some modules Perl does that I guess - what about Python?



Mon May 30 12:33:36 2005: 592   TonyLawrence

gravatar
I'm not a big OO fan, so I pay very little attention to those capabilities in any language. I'm not anti-OO: I think it is good in some places, but usually not for the kinds of things I do.





Tue Jul 26 09:20:43 2005: 870   drag


Interesting.

I played around with python a bit more then perl. I like how it's generally easier to read.

Haven't quite been able to get my head around making my own classes yet, but I am working on it.

I don't know what you mean by 'polymorphism' and 'encapsulation' and such.. but Python is suppose to be very OO-freindly from what I understand. If your building a application, for instance, and you run into a part that is very performance-oriented bottleneck you can then go and rewrite that part of the program in C, which isn't to hard since it has a c-alike syntax (and I think there are things that will take python code and translate it to c for you, not sure). Then you can compile it and import that back into your python program as a module. You can import other programs back into your python program and use their functions and classes and such in your programs..

For instance if you have a program and you want to have a GUI for it, and a command line interface for it.. You could create a core functionality with the main logic of the program as a seperate peice then create a GUI front end, and then a seperate command line front end then import that functionality into your programs.

Also Python isn't a interpreted language so much like Basic is.. It's compiled into optimized bitecode in the form of object files the first time you call something and then you use that. Any changes to the source code that you call will cause it to re-generate the bitcode..

Python is unusual because it's 'strongly typed' and 'dynamicly typed'. It's strongly typed like Java.. you can't simply change types depending on the circumstances, but it's dynamicly typed like VBScript were the program decides what type on the fly when you create the the datatype.

There are a few conventions that you have to get used to. For instance the tuple thing... generally you use paranthesis to easily denote tuple creation, and you use capitolization to denote variables and such, depends on the programmer I support.

This=('tuple',)
type(This)

That's a tuple, obviously.

This=['tuple',)
type(This)

That's a list. So you can create your datatypes specificly if you like.

Another convention is that if your working with numbers...
This=4
type(This)

Will be a int.

This=4.0
type(This)

Will be a float.

But you can specificy if you want..
This=float(4)
type(This)

that will be a float. And:
This=int(4.0)
type(This)

will be a init. It rounds down, so...
This=int(4.9)
print This
4

This=str(4.9)
type(This)
will be a string...

This is kinda handy:
This=hex(454)
print This
'0x1c6'

You can do the same thing with tuple() and list() if you want and there are a couple other datatypes that I forget.. But you have to be carefull...

This=tuple("tuple")
print This
('t', 'u', 'p', 'l', 'e')

When doing mathmatics generally you want to add one number with a decemal to it just so you get the result of the entire formula as a float.

That's what I use python mostly for... Mathmatics. It's very handy for that sort of thing. Lots of libraries and handy dandy functions and such you can import from other programs. Also very high-level math is attanable as long as you mind the limitations. There are scientific modules and engineering stuff you can use. I seen on PBS once that this professor programmed 3-d plotting of tornadoes based on his formulas for weather simulation entirely in python. So I think that it's commonly used programming language by enginneers and such.

In fact I prefer to use python to scientific calculators if I can.

I don't think that math and such is a strong point for Perl, although I never realy use perl much at all, so I can't be sure. But it's a hell of a lot better then Bash.

Official docs...
http://www.python.org/doc/
They talk a bit about other languages and do comparisions.
One odd thing about Python is that although it's slow (and can be sped up sometimes by liberal applications of the 'psycho' module), it has a agressive garbage collector so the memory footprints of python programs remain small compared to stuff like Java.

If your a experianced programmer then this book is probably quite handy introduction to python:
http://diveintopython.org/

All in all it's actually a 'fun' programming language. There are modules for making things (relatively) easy, lots of sharing of code. Lots is out there..
you have a weird data collection card? There is probably somebody using python modules for data collection. You want to make games.. there are several python-related gaming engines and library support like libsdl modules. It's used as a scripting language for Blender, a popular and full-featured 3d modeling suite. You need more 'exact' 3d solutions for moduling things and use in programs there are several commercial and free software solutions to choose from.

All sorts of stuff. And if your making things for the win32 platform you can even compile your python programs into self-contained .exe executables so that the end users don't have to track down all these dependancies and libraries and such.



Tue Jul 26 14:39:17 2005: 876   BigDumbDinosaur


Also Python isn't a interpreted language so much like Basic is.. It's compiled into optimized bitecode...

However, the "bytecode" itself is interpreted.

You should know that all forms of Business BASIC are stored in optimized form (tokenized or bytecode, if you prefer). For example, Thoroughbred BASIC, which is an environment in which I've done a lot of development, reduces verbs such as PRINT or READ to byte or word sized tokens, generates an internal symbol table for fast variable and branch target lookup, and generally compacts the program (as much as 20 percent smaller than the source text). Only lame BASIC versions like MS-DOS's Qbasic store the program in ASCII text form, making for slow interpretation. Even the BASIC interpreter that ran on the Commodore 64 tokenized programs.



Fri Sep 12 18:19:45 2008: 4545   anonymous


That's an interesting post. I'm an experienced Perl programmer (except in regard to Perl OOP, modules and XS - I understand most it them but didn't work much on that yet) and recently started learning Python. Here's what I'd like to add/comment from your article:

What I like:

- Interactive interpreter, dir and help functions

I often write small Perl programs, pack them on a -e argument or write them in a bash heredoc to try new stuff and alternative ways of doing things. I really like the interactive python interpreter, and the dir function and embedded help make it even more useful. I can test stuff live, easily and with an history buffer. This is extremely useful when learning or perfecting programing language skills!

- Simple use of class and functions

It always bothered me how it is to write a Perl module, or move functions away in a separate file (I've done the latter sometime but only when there were very good incentives to do so). Python makes it so simple, you can move you functions around just like you do copy-paste. Same simplicity goes for classes, which means Python modules are just as simple to write as Python programs.

It's also funny how simple it is to add unit testing to your functions by adding it to an "if __name__ == '__main__':" condition in you libs then just run them.

- Variable prefixes, types

Unlike you, I don't miss at all variable prefixes. I don't tend to rely on them to know what a variable is. OTOH, I really like the simplicity in acceding nested variables in Python. Perl has many different syntaxes to access "structures", variable referencing, dereferencing, etc, Each data type has it's own syntax and it still sometimes confuse me after many years on complex structures (i.e. with many levels of nesting of different types). Python is much simpler; there's only one way to do it and the syntax roughly the same whenever you access a dictionary, list or a tuple.

- Passing references

I like how Python pass references by default. Ex:

>>> foo = [1,2,3]
>>> bar = foo
>>> bar.append(4)
>>> print foo
[1, 2, 3, 4]


What I dislike

The only thing that I really miss from Perl is it's strict mode in regard to declaring variables. In strict mode, if you mistype a variable in an assignment within a code block, Perl will complain because you didn't declared it with my(). Also, if you accidentally re-declare the same variable, it will print a warning too. This can be very handy catching common typos and errors.

"i++" would be nice but it's not much different than "i+=1", which is supported... And I really don't miss the $_ (IMHO it make code clearer too).



Sat Mar 27 04:37:47 2010: 8283   anonymous

gravatar


Wow, you should really add a date to your articles. At least, I didn't find any scrolling over it three times.
Anyway, since there are comments from 2005, I guess the article isn't that much older. It is a very uninformed article though. To anyone who has been programming both perl and python extensively, it is immediately clear that you didn't give python more than 30 minutes and went back to "what you know". You really could have given it a weekend at least...

Most of your criticism would have cleared up by reading PEP8 and "The Zen of Python", which are two of the most basic sources for python philosophy.

Also, one element tuples are usually declared like ('my string',), "a += 1" is equivalent to (and easier to grasp than) "a++" and there is no _. ($_ is really one of the worst ideas of perl, btw.)

Don't get me wrong, I appreciate your effort, but you should really have given it some more time instead of giving uninformed statements (which get top google ratings on "python vs. perl" btw).



Sat Mar 27 12:39:17 2010: 8284   TonyLawrence

gravatar


Yes, I've been going back and making the date easier to find (it's always available through the copyright link but needs to be easier). This article was from 2003; it takes a while to get to everything :-)

I can't control what Google gives top ratings to. That usually comes from lots of other sites linking to this - which might indicate the post has value to someone.

I think I made it very plain that my intent was just to explore Python briefly and try to see why each camp is sometimes so unhappy with the other. I think I accomplished that, but if you disagree, that's fine. If you'd like to write a more complete article, I'd be happy to publish it: http://aplawrence.com/publish.html



Mon May 17 12:16:08 2010: 8605   anonymous
http://www.x0.org.ua
gravatar



and what is actually an advantage perl?






Mon May 17 12:31:32 2010: 8606   TonyLawrence

gravatar


I thought I made it clear why *I* like Perl and the Python fans were expansive with their arguments.

You are free to have your own opinions on either side.



Wed Jun 2 09:31:58 2010: 8651   anonymous

gravatar


Hi all,
Pls read about perl moose and catalyst. perl is best.
Try parsing a big file with python and u will know that perl is faster than python. Also, I cant or u cant always use pypy (a python module) for every other program.

cheers,
Truman

Don't miss responses! Subscribe to Comments by RSS or by Email

Click here to add your comments


If you want a picture to show with your comment, go get a Gravatar

Kerio Samepage


Have you tried Searching this site?

Unix/Linux/Mac OS X support by phone, email or on-site: Support Rates

This is a Unix/Linux resource website. It contains technical articles about Unix, Linux and general computing related subjects, opinion, news, help files, how-to's, tutorials and more. We appreciate comments and article submissions.

Publishing your articles here

Jump to Comments



Many of the products and books I review are things I purchased for my own use. Some were given to me specifically for the purpose of reviewing them. I resell or can earn commissions from the sale of some of these items. Links within these pages may be affiliate links that pay me for referring you to them. That's mostly insignificant amounts of money; whenever it is not I have made my relationship plain. I also may own stock in companies mentioned here. If you have any question, please do feel free to contact me.

I am a Kerio reseller. Articles here related to Kerio products reflect my honest opinion, but I do have an obvious interest in selling those products also.

Specific links that take you to pages that allow you to purchase the item I reviewed are very likely to pay me a commission. Many of the books I review were given to me by the publishers specifically for the purpose of writing a review. These gifts and referral fees do not affect my opinions; I often give bad reviews anyway.

We use Google third-party advertising companies to serve ads when you visit our website. These companies may use information (not including your name, address, email address, or telephone number) about your visits to this and other websites in order to provide advertisements about goods and services of interest to you. If you would like more information about this practice and to know your choices about not having this information used by these companies, click here.

pavatar.jpg

This post tagged:

       - Perl
       - Programming



















My Troubleshooting E-Book will show you how to solve tough problems on Linux and Unix systems!


book graphic unix and linux troubleshooting guide



Buy Kerio from a dealer
who knows tech:
I sell and support

Kerio Connect Mail server, Control, Workspace and Operator licenses and subscription renewals



Click and enter your name and phone number to call me about Kerio® products right now (Flash required)