Python vs. Perl

M

Michael McGarry

Hi,

I am just starting to use Python. Does Python have all the regular
expression features of Perl?

Is Python missing any features available in Perl?

Thanks,

Michael
 
R

Roy Smith

Michael McGarry said:
I am just starting to use Python. Does Python have all the regular
expression features of Perl?

I can't vouch for "all", but the Python reference manual for the "re"
module (http://docs.python.org/lib/module-re.html) says, "This module
provides regular expression matching operations similar to those found
in Perl".
Is Python missing any features available in Perl?

Are you talking specifically about regex, or about the language in
general? If the latter, then the answer is "Yes, and this is a Good
Thing". If you meant the former, then I suspect the answer is that
anything you can do with a Perl regex you can also do with a Python
regex. I'm a pretty heavy regex user, and I've never found anything I
wanted to do which I was unable to.

The biggest difference between regex support in Perl and Python is that
Perl has regex syntax built into the core language, while Python does it
with a module that you have to import and then call functions inside
that module. Which you like better is a matter of personal opinion.
Like most Perl-Python feature comparisons, the Perl version usually ends
up more compact, but the Python version ends up easier to understand.
 
C

Christopher De Vries

Roy Smith already touched on regular expressions, but as far as
features go, I would say that the real difference between python and
perl is not in the features, but in the philosophy. It seems to me that
any program you can write in python could also be written in perl. What
it comes down to for me was which language most fit the way I tend to
think. I decided python was that language, and I found everything very
intuitive. I have a good friend who thinks in perl and is very
productive using it.

Other people might disagree, but when I was looking at perl and python
I borrowed recent copies of "Learning Perl" and "Learning Python" from
the O'Reilly series and after reading each, decided I preferred python.
You can find out about most of the features in those books.

Chris
 
L

loritsch

Christopher said:
Roy Smith already touched on regular expressions, but as far as
features go, I would say that the real difference between python and
perl is not in the features, but in the philosophy.

To help aid in this discussion, the following Python and Perl
philosophy links might be useful:
http://c2.com/cgi/wiki?PythonPhilosophy
http://www.maths.adelaide.edu.au/~cmc/tutorials/perlintro/x175.html

Now, so that I don't start another Python vs. Perl flamewar, I'd like
to inform everyone that I'm about to make a few generalizations based
on my experience. As should be understood implicitly, one man's
experience is not the experience of everyone...

As a user of both languages, I've found that what Perl and Python
programmers have in common is that they were looking for a better tool
when they stumbled across their language of choice... After all, one
can be productive in both languages.

What I've also noticed that people who use Perl tended to start using
it as a way to make either C or shell scripting tasks easier (after
all, this is Perl's original intended audience). Many of these
developers have gone on to use Perl for bigger and better things, but
without a lot of discipline (use strict, and a lot of work with the
Exporter), Perl doesn't scale very well to large projects. My belief
is that Perl's strength (TMTOWTDI) is also it's greatest weakness.

I've also noticed that Python programmers tend to be a more diverse
lot. While Guido originally intended Python to be a second language
for C/C++ developers, it is also quite useful as a first language.
Python's philosophy is more that there should a clear understandable
way to do things, and that readability counts. That is not to say you
can't perform tasks in multiple ways, it is just to say that Python
doesn't believe in TMTOWTDI as Perl does.

So the bottom line is this. In choosing Perl or Python, the real
difference should be your mindset, and what you intend to use it for.
If you want a multiparadigm programming language that offers wonderful
OO support, is easy to learn, and in which you will naturally write
maintainable code, choose Python.

On the other hand, if you are looking for a language to text-processing
and to perform short quick shell scripting like tasks, choose Perl.
While both languages can be used to perform both sets of tasks, my
belief is that one should pair a language and a task by strengths
rather than what can be done in each language.
I hope this helps!

Michael Loritsch
 
M

Michael McGarry

To help aid in this discussion, the following Python and Perl
philosophy links might be useful:
http://c2.com/cgi/wiki?PythonPhilosophy
http://www.maths.adelaide.edu.au/~cmc/tutorials/perlintro/x175.html

Now, so that I don't start another Python vs. Perl flamewar, I'd like
to inform everyone that I'm about to make a few generalizations based
on my experience. As should be understood implicitly, one man's
experience is not the experience of everyone...

As a user of both languages, I've found that what Perl and Python
programmers have in common is that they were looking for a better tool
when they stumbled across their language of choice... After all, one
can be productive in both languages.

What I've also noticed that people who use Perl tended to start using
it as a way to make either C or shell scripting tasks easier (after
all, this is Perl's original intended audience). Many of these
developers have gone on to use Perl for bigger and better things, but
without a lot of discipline (use strict, and a lot of work with the
Exporter), Perl doesn't scale very well to large projects. My belief
is that Perl's strength (TMTOWTDI) is also it's greatest weakness.

I've also noticed that Python programmers tend to be a more diverse
lot. While Guido originally intended Python to be a second language
for C/C++ developers, it is also quite useful as a first language.
Python's philosophy is more that there should a clear understandable
way to do things, and that readability counts. That is not to say you
can't perform tasks in multiple ways, it is just to say that Python
doesn't believe in TMTOWTDI as Perl does.

So the bottom line is this. In choosing Perl or Python, the real
difference should be your mindset, and what you intend to use it for.
If you want a multiparadigm programming language that offers wonderful
OO support, is easy to learn, and in which you will naturally write
maintainable code, choose Python.

On the other hand, if you are looking for a language to text-processing
and to perform short quick shell scripting like tasks, choose Perl.
While both languages can be used to perform both sets of tasks, my
belief is that one should pair a language and a task by strengths
rather than what can be done in each language.
I hope this helps!

Michael Loritsch
Thank you all for your input. Please feel free to keep this discussion
going.

I intend to use a scripting language for GUI development and front end
code for my simulations in C. I want a language that can support SQL,
Sockets, File I/O, and shell interaction.

I welcome any opinions on this.
 
C

Christos TZOTZIOY Georgiou

Thank you all for your input. Please feel free to keep this discussion
going.

I intend to use a scripting language for GUI development and front end
code for my simulations in C. I want a language that can support SQL,
Sockets, File I/O, and shell interaction.

I welcome any opinions on this.

I don't know if my opinion will help, but I know if you follow my
advice, it will be enlightening :)

Both languages cover all of your requirements. So read as much
documentation needed to write some simple programs as examples doing
similar tasks to the one you want in *both* languages. Test them that
they work. Then forget about your problems. Go to an island. Dream.
Relax. Come back without explanations six months later, and if they
take you back in the same company, read *both* of your example programs.
You'll know then which language to select (I would select the language
of the island natives, but that's another story :)
 
T

Timo Virkkala

Christos said:
Both languages cover all of your requirements. So read as much
documentation needed to write some simple programs as examples doing
similar tasks to the one you want in *both* languages. Test them that
they work. Then forget about your problems. Go to an island. Dream.
Relax. Come back without explanations six months later, and if they
take you back in the same company, read *both* of your example programs.
You'll know then which language to select (I would select the language
of the island natives, but that's another story :)

That's unfair! That approach leads to Python every time!

Oh wait, that was the purpose.. :)
 
J

Jon Perez

Michael said:
I intend to use a scripting language for GUI development and front end
code for my simulations in C. I want a language that can support SQL,
Sockets, File I/O, and shell interaction.

In my experience, Python is definitely much more suitable than Perl
for the first four areas mentioned in the last sentence. For the
last area, I'm not sure, but Python's capabilities in this area are
also quite good.

For GUI development and front end, Python most likely has better
facilities than Perl, but still leaves a lot to be desired (after
getting a taste of Delphi 3rd party VCL components, all other RAD
environments pale in comparison).
 
I

Ian Bicking

Jon said:
In my experience, Python is definitely much more suitable than Perl
for the first four areas mentioned in the last sentence. For the
last area, I'm not sure, but Python's capabilities in this area are
also quite good.

Shell interaction (or rather, external process interaction) is a lot
better with Python 2.4's subprocess module. Better or worse than Perl?
I'm not sure; generally I'd guess better, as it avoids the shell with
all the shell's issues, and provides a more controlled programmatic way
of interacting with subprocesses. OTOH, Perl might have perfectly good
modules for doing the same thing. I can only say it's been missing for
a while in Python, and it's good to see this done right.
 
K

Keith Dart

Ian said:
Shell interaction (or rather, external process interaction) is a lot
better with Python 2.4's subprocess module. Better or worse than Perl?
I'm not sure; generally I'd guess better, as it avoids the shell with
all the shell's issues, and provides a more controlled programmatic way
of interacting with subprocesses. OTOH, Perl might have perfectly good
modules for doing the same thing. I can only say it's been missing for
a while in Python, and it's good to see this done right.

Yow, I must not get picked up in Google enough. ;-) The "proctools"
module in the pyNMS package <http://sourceforge.net/projects/pynms/> has
been around for years. I use it all the time for shell-like stuff. There
is also an "expect" module, and the "termtools" module. If you need a
more complete process spawning and controlling framework then use pyNMS.
It can "juggle" multiple processes, reaps child status (no
zombies), operates asynchronously (The ProcManager object is a SIGCHLD
handler), and works with pty's and pipes. It also offers a "thread-like"
interface for Python subprocesses (uses fork). Can leave some fd's open
that you specify, can run the subprocess as a different user, and more...


Check it out.



--
\/ \/
(O O)
-- --------------------oOOo~(_)~oOOo----------------------------------------
Keith Dart <[email protected]>
public key: ID: F3D288E4
============================================================================
 
K

Keith Dart

Keith said:
Yow, I must not get picked up in Google enough. ;-) The "proctools"
module in the pyNMS package <http://sourceforge.net/projects/pynms/> has
been around for years. I use it all the time for shell-like stuff. There
is also an "expect" module, and the "termtools" module. If you need a
more complete process spawning and controlling framework then use pyNMS.
It can "juggle" multiple processes, reaps child status (no
zombies), operates asynchronously (The ProcManager object is a SIGCHLD
handler), and works with pty's and pipes. It also offers a "thread-like"
interface for Python subprocesses (uses fork). Can leave some fd's open
that you specify, can run the subprocess as a different user, and more...


Check it out.

Oh, I forgot to mention that it also has a more user- and
programmer-friendly ExitStatus object that processess can return. This
is directly testable in Python:

proc = proctools.spawn("somecommand")
exitstatus = proc.wait()

if exitstatus:
print "good result (errorlevel of zero)"
else:
print exitstatus # prints message with exit value






--
\/ \/
(O O)
-- --------------------oOOo~(_)~oOOo----------------------------------------
Keith Dart <[email protected]>
vcard: <http://www.kdart.com/~kdart/kdart.vcf>
public key: ID: F3D288E4 URL: <http://www.kdart.com/~kdart/public.key>
============================================================================
 
K

Keith Dart

Keith said:
Yow, I must not get picked up in Google enough. ;-) The "proctools"
module in the pyNMS package <http://sourceforge.net/projects/pynms/> has
been around for years. I use it all the time for shell-like stuff. There
is also an "expect" module, and the "termtools" module. If you need a
more complete process spawning and controlling framework then use pyNMS.
It can "juggle" multiple processes, reaps child status (no
zombies), operates asynchronously (The ProcManager object is a SIGCHLD
handler), and works with pty's and pipes. It also offers a "thread-like"
interface for Python subprocesses (uses fork). Can leave some fd's open
that you specify, can run the subprocess as a different user, and more...


Check it out.

Oh, I forgot to mention that it also has a more user- and
programmer-friendly ExitStatus object that processess can return. This
is directly testable in Python:

proc = proctools.spawn("somecommand")
exitstatus = proc.wait()

if exitstatus:
print "good result (errorlevel of zero)"
else:
print exitstatus # prints message with exit value






--
\/ \/
(O O)
-- --------------------oOOo~(_)~oOOo----------------------------------------
Keith Dart <[email protected]>
vcard: <http://www.kdart.com/~kdart/kdart.vcf>
public key: ID: F3D288E4 URL: <http://www.kdart.com/~kdart/public.key>
============================================================================
 
N

Nick Craig-Wood

Keith Dart said:
Oh, I forgot to mention that it also has a more user- and
programmer-friendly ExitStatus object that processess can return. This
is directly testable in Python:

proc = proctools.spawn("somecommand")
exitstatus = proc.wait()

if exitstatus:
print "good result (errorlevel of zero)"
else:
print exitstatus # prints message with exit value

This sounds rather like the new subprocess module...
import subprocess
rc = subprocess.call(["ls", "-l"])
total 381896
-rw-r--r-- 1 ncw ncw 1542 Oct 12 17:55 1
[snip]
-rw-r--r-- 1 ncw ncw 713 Nov 16 08:18 z~0

IMHO the new subprocess module is a very well thought out interface...
 
K

Keith Dart

Nick said:
Keith Dart said:
Oh, I forgot to mention that it also has a more user- and
programmer-friendly ExitStatus object that processess can return. This
is directly testable in Python:

proc = proctools.spawn("somecommand")
exitstatus = proc.wait()

if exitstatus:
print "good result (errorlevel of zero)"
else:
print exitstatus # prints message with exit value


This sounds rather like the new subprocess module...

import subprocess
rc = subprocess.call(["ls", "-l"])

total 381896
-rw-r--r-- 1 ncw ncw 1542 Oct 12 17:55 1
[snip]
-rw-r--r-- 1 ncw ncw 713 Nov 16 08:18 z~

0

But this evaluates to False in Python, but True in a shell. It also
requires an extra check for normal exit, or exit by a signal. The
proctools ExitStatus object avaluates to True only on a normal exit,
period. Thus it follows a shell semantics for clarity. You cannot do
this with the subprocess module:

if rc:
print "exited normally"


But in proctools, the exitstatus is an object that evaluates True only
for normal exit.

import proctools
proc = proctools.spawnpipe("ls -l")
print proc.read()
....
print proc.exitstatus
ls: Exited normally.


proc = proctools.spawnpipe("ls -l xx")
print proc.read()
'ls: xx: No such file or directory\n'

print proc.exitstatus
ls: Exited abnormally with status 1.

if proc.exitstatus:
print "returned normally"


But you can get the integer return value, if you want it, like this:
int(proc.exitstatus)

or query it with methods returning booleans:

exitstatus.exited()
exitstatus.signalled()
exitstatus.stopped()

Also, proctools lets you use a pty, if you choose. Not every program
works well from a pipe.
IMHO the new subprocess module is a very well thought out interface...

The proctools Process object presents a file-like object to the rest of
Python, which makes a process polymorhic with any other file, pipe or
socket object. It has the usual read, write, readline, and readlines
methods. It can also be made non-blocking, and you can have many open at
once. In addition, there are special methods for controlling the
sub-process: You can kill it, stop it, re-start it, clone it, wait on
it, and get stats from it. The stat() method returns a ProcStat object,
which has attributes like what you get from the 'ps' program. Need to
know the process's RSS? No problem. It also supports logging to a log
file, and on-exit callback for persistent process requirements.

You always invoke the spawn* functions with a string. This is parsed by
a shell-like parser (the shparser module that comes with it), but no
/bin/sh is invoked. The parser can handle single and double quotes, and
backslash escapes.

Alas, one thing the proctools module does not do well yet is create a
pipeline. I have plans to fix that.

It does not work with MS Windows, but can work with cygwin on Windows.


Whew... and I have not even covered the ProcessManager object...



--
\/ \/
(O O)
-- --------------------oOOo~(_)~oOOo----------------------------------------
Keith Dart <[email protected]>
vcard: <http://www.kdart.com/~kdart/kdart.vcf>
public key: ID: F3D288E4 URL: <http://www.kdart.com/~kdart/public.key>
============================================================================
 
D

Donn Cave

|>> Oh, I forgot to mention that it also has a more user- and
|>> programmer-friendly ExitStatus object that processess can return. This
|>> is directly testable in Python:
|>>
|>> proc = proctools.spawn("somecommand")
|>> exitstatus = proc.wait()
|>>
|>> if exitstatus:
|>> print "good result (errorlevel of zero)"
|>> else:
|>> print exitstatus # prints message with exit value

This is indeed how the shell works, though the actual failure value
is rarely of any interest. It's also in a more general sense how
C works - whether errors turn out to be "true" or "false", in either
case you test for that status (or you don't.)

Python doesn't work that way, there is normally no such thing as
an error return. An idiomatic Python interface would be

try:
proc = proctools.spawn(command)
proc.wait()
print 'good result'
except proctools.error, ev:
print >> sys.stderr, '%s: %s' % (proc.name, ev.text)

[... list of features ...]

| You always invoke the spawn* functions with a string. This is parsed by
| a shell-like parser (the shparser module that comes with it), but no
| /bin/sh is invoked. The parser can handle single and double quotes, and
| backslash escapes.

It was sounding good up to here. A lot depends on the quality of
the parser, but it's so easy to support a list of arguments that
gets passed unmodified to execve(), and such an obvious win in the
common case where the command parameters are already separate values,
that an interface where you "always" have to encode them in a string
to be submitted to your parser seems to be ignoring the progress that
os.spawnv and popen2.Popen3 made on this. Of course you don't need
to repeat their blunders either and accept either string or list of
strings in the same parameter, which makes for kind of a shabby API,
but maybe a keyword parameter or a separate function would make sense.

Donn Cave, (e-mail address removed)
 
K

Keith Dart

Donn said:
|>> if exitstatus:
|>> print "good result (errorlevel of zero)"
|>> else:
|>> print exitstatus # prints message with exit value

This is indeed how the shell works, though the actual failure value
is rarely of any interest. It's also in a more general sense how
C works - whether errors turn out to be "true" or "false", in either
case you test for that status (or you don't.)

Python doesn't work that way, there is normally no such thing as
an error return. An idiomatic Python interface would be

try:
proc = proctools.spawn(command)
proc.wait()
print 'good result'
except proctools.error, ev:
print >> sys.stderr, '%s: %s' % (proc.name, ev.text)


Your first statement is exactly right. One does not always care about
the return value of an external process. And some programs still return
an undefined value, even when successful. Therefore, I don't want to
always have to wrap a call to an external program in a try..except
block. Thus, it returns an ExitStatus object that you can easily test
true-false with as in a shell, or get the actual value if you need it.
Otherwise, just ignore it.

[... list of features ...]

| You always invoke the spawn* functions with a string. This is parsed by
| a shell-like parser (the shparser module that comes with it), but no
| /bin/sh is invoked. The parser can handle single and double quotes, and
| backslash escapes.

It was sounding good up to here. A lot depends on the quality of
the parser, but it's so easy to support a list of arguments that
gets passed unmodified to execve(), and such an obvious win in the
common case where the command parameters are already separate values,
that an interface where you "always" have to encode them in a string
to be submitted to your parser seems to be ignoring the progress that
os.spawnv and popen2.Popen3 made on this. Of course you don't need
to repeat their blunders either and accept either string or list of
strings in the same parameter, which makes for kind of a shabby API,
but maybe a keyword parameter or a separate function would make sense.

Actually, an earlier version of proctools did take a list. However,
after much usage I realized that in most cases what I got was a string
to begin with. Either from user input or read from a file. I also found
it easier to construct command-lines using the string-mod operator,
substituting various attributes into option-value pairs in arbitrary
ways. I was having to split/parse a string so often I decided to just
make the Process object parse it itself. The shparser module has been
perfectly adequate for this, and you can pass to the Process object
pretty much the same string as you would to a real shell (thus making it
easier to use for *nix people). I could add a list-input check, but
likely I would never use it.



--
\/ \/
(O O)
-- --------------------oOOo~(_)~oOOo----------------------------------------
Keith Dart <[email protected]>
public key: ID: F3D288E4
============================================================================
 
N

Nick Craig-Wood

Keith Dart said:
Nick said:
This sounds rather like the new subprocess module...
import subprocess
rc = subprocess.call(["ls", "-l"])

total 381896
-rw-r--r-- 1 ncw ncw 1542 Oct 12 17:55 1
[snip]
-rw-r--r-- 1 ncw ncw 713 Nov 16 08:18 z~

0

But this evaluates to False in Python, but True in a shell.

There are many ways for a program to fail (non-zero exit codes) but
only one way for it to succeed (zero exit code). Therefore rc should
be 0 for success.

IMHO Shell semantics are nuts (0 is True - yeah!) - they hurt my head
every time I have to use them ;-)
It also requires an extra check for normal exit, or exit by a
signal.
import subprocess
subprocess.call(["sleep", "60"]) -11
# I killed the sleep process with a SEGV here from another xterm
subprocess.call(["sleep", "asdfasdf"])
sleep: invalid time interval `asdfasdf'
Try `sleep --help' for more information.
1
Signals are -ve, exit codes are +ve which seems perfect. Exit codes
can only be from 0..255 under linux. Signals go from -1 to -64.
The proctools ExitStatus object avaluates to True only on a normal
exit, period. Thus it follows a shell semantics for clarity. You
cannot do this with the subprocess module:

if rc:
print "exited normally"

Actually I think

if rc == 0:
print "exited normally"

is exactly equivalent!

[snip]
It does not work with MS Windows

I like python because I can write stuff on linux and it works on
windows without too much effort, and in general I try not to use
modules which don't work on both platforms.
 
K

Keith Dart

Nick said:
There are many ways for a program to fail (non-zero exit codes) but
only one way for it to succeed (zero exit code). Therefore rc should
be 0 for success.

Exactly. And as a convenience the ExitStatus object of proctools handles
that for you.

As a general rule, I believe Python interfaces should be more abstract
and object-oriented. I don't think the users of my framework (myself
included) should have to know or deal with the fact that "zero means
good". You only need to know that if the ExitStatus object you get
avaluates to True, it is a "good" exit.
IMHO Shell semantics are nuts (0 is True - yeah!) - they hurt my head
every time I have to use them ;-)

Exactly, and that is why the proctools framework hides that from the
user-programmer.

import subprocess
subprocess.call(["sleep", "60"])

-11

# I killed the sleep process with a SEGV here from another xterm

Python> import proctools
Python> print proctools.call("sleep 60")
sleep exited by signal 11.

# same here... sent SEGV. which is easier to understand what is going on?
(BTW, I just added a "call" function to proctools with similiar
functionality)

subprocess.call(["sleep", "asdfasdf"])

sleep: invalid time interval `asdfasdf'
Try `sleep --help' for more information.
1

Python> print proctools.call("sleep asdf")
sleep: Exited abnormally with status 1.

Signals are -ve, exit codes are +ve which seems perfect. Exit codes
can only be from 0..255 under linux. Signals go from -1 to -64.

And why should my API user-programmers need to know that? That is just
too... low-level.

Actually I think

if rc == 0:
print "exited normally"

is exactly equivalent!

Yes, but requires the programmer to know that zero is good, and signals
are negative. Again, the proctool's ExitStatus makes that more abstract
for you (as Python interfaces should be) and provides test methods if
you need them.

Python> rc = proctools.call("sleep asdf")
Python> rc.exited()
True
Python> rc.signalled()
False
Python> int(rc)
1
# Note that you can still get the exit value for those programs that
# return something meaningful.

Python> rc = proctools.call("sleep 60")
# send SEGV
Python> rc.signalled()
True
I like python because I can write stuff on linux and it works on
windows without too much effort, and in general I try not to use
modules which don't work on both platforms.

Sorry for you. I like Python becuase it allows me to write good, solid
programs easily and quickly. I try to make my libraries facilitate that,
and also be easy to use for beginning Python programmers. Python on
Linux is a powerful combination, and I cannot fathom why someone would
choose anything less. (I would concede that Python on Darwin is also good)



--
\/ \/
(O O)
-- --------------------oOOo~(_)~oOOo----------------------------------------
Keith Dart <[email protected]>
public key: ID: F3D288E4
============================================================================
 
T

Terry Hancock

I intend to use a scripting language for GUI development and front end
code for my simulations in C. I want a language that can support SQL,
Sockets, File I/O, and shell interaction.

In my humble opinion, anything complicated enough to need a GUI is
something you want to write in Python, not Perl. Python is a very
object-oriented language. I know you can do OOP in Perl, but it was
not really designed for it.


As for your earlier regex question, Python and Perl regex syntax is
quite simple, but Python puts regexes in strings, which allows you to
do some nice tricks using Python string handling on the regexes.

Some people have demonstrated how this can be used to make
regexes much better source-documented (and regexes are notoriously
hard to read, so this is worthwhile!). E.g.:

digit = r'\d'
phone_number_re = re.compile(digit*3 + '-' + digit*4)

In general, Python has substantial support for "literate programming"
and/or self-documentation. As a person who programs only part-time,
while having many non-programming tasks which I have to juggle, this
is invaluable. Python is the only language I could reasonably expect to
be productive in while caring for a toddler. ;-)

As it sounds like you are doing scientific work, you may well find that
this serves you as well.

Cheers,
Terry
 
D

Dan

I'm inexperienced in both languages, and am toying around with
both now, so I offer these comments with warnings of the blind
leading the blind.

As far as regular expressions go I can't offer much information.
They both meet my needs. I prefer the Python syntax, however:
it is possible in both languages to compile a regex once and use
it many times, but it is more plainly specified in Python.

One difference I've noticed between the two languages is variable
scope. By default, Perl variables are global, but there is a "my"
keyword that makes scope behave much as in C:

#!/usr/bin/env perl
my $foo = "globally defined \$foo";
sub func_2 {
print "func_2: $foo\n";
}
sub func_1 {
my $foo = "func_1 defined \$foo";
print "func_1: $foo\n";
if (1) {
my $foo = "if_block defined \$foo";
print "if_block: $foo\n";
}
print "func_1: $foo\n";
func_2()
}
print "main: $foo\n";
func_1();
func_2();
print "main: $foo\n";

Here's the output. Note that the assignment within the if_block
only holds within that block (it would have held to the end of
func_1() if not for the "my" keyword). Note that the call of
func_2() from within func_1() does _not_ see the effect of the
assignment in func_1().

main: globally defined $foo
func_1: func_1 defined $foo
if_block: if_block defined $foo
func_1: func_1 defined $foo
func_2: globally defined $foo
func_2: globally defined $foo
main: globally defined $foo

In Python, unless I just haven't figured it out yet, you can't
quite get this C-like scoping. You can have global variables,
and variables local to functions, but I don't see any way to get
a variable local to an if block.

There is another keyword in Perl called "local" that makes
variables behave much like those of Emacs Lisp. Take this
program for example:

#!/usr/bin/env perl
$foo = "globally defined \$foo";
sub func_2 {
print "func_2: $foo\n";
}
sub func_1 {
local $foo = "func_1 defined \$foo";
print "func_1: $foo\n";
func_2()
}
print "main: $foo\n";
func_1();
func_2();
print "main: $foo\n";

Here's the output:

main: globally defined $foo
func_1: func_1 defined $foo
func_2: func_1 defined $foo
func_2: globally defined $foo
main: globally defined $foo

Notice that the first call of func_2() from func_1() _does_ see
the "local" assignment in func_1(), but that once func_1()
returns the global definition of $foo is restored and is now in
effect when func_2() is called from main. I don't believe
Python has anything like this, but I don't know Python well
enough to be sure. I can't think of how this would be useful in
Perl or Python, but it seems useful in Emacs Lisp.

Another difference between the languages is the amount of error
checking done at compile time. Perl seems to catch more errors
at compile time.

You asked if Python is missing any features of Perl. Perl has a
"tainted" mode that guards against insecure use of data provided
by users. I don't know that Python has any equivalent. I've
not used this, and I don't know how robust it's considered.

Another advantage of Perl is wider availability. Until about a
year and a half ago, my primary environment was VMS. And the
newest version of Python I could find for VMS was 1.4 when the
latest Python was 2.2.2. Perl's well supported on VMS, and is
embeddable in VMS DCL command scripts.

But, for me, each language has one big advantage over the other.
Perl is the scripting language almost universally used in my
workplace. There are a lot of existing scripts and lots of
local expertise in Perl. I don't know of any existing Python
scripts, or Python users, in my building. That's Perl's
strength in my world. On the other hand, I find Perl's syntax
really hard to deal with. I'm not a programmer, I'm an engineer
who infrequently needs to write a small program. So, I write
something, and then find that I need to modify it or write
something new six months later. I invariably forget everything
I know about Perl in six months. I've been "learning" Perl
since 1998, but find I keep reverting to C (or even Emacs Lisp!)
for small, simple programs because I can't remember how to do it
in Perl. So, I thought I'd give Python a try. The syntax
certainly seems a lot cleaner and easier to remember. We'll see
how it goes.

/Dan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top