How to best explain a "subtle" difference between Python and Perl ?

Jonathan Gardner jgardner at jonathangardner.net
Tue Aug 12 20:12:39 EDT 2008


On Aug 12, 9:17 am, Palindrom <demarc... at gmail.com> wrote:
> Hi everyone !
>
> I'd like to apologize in advance for my bad english, it's not my
> mother tongue...
>
> My girlfriend (who is a newbie in Python, but knows Perl quite well)
> asked me this morning why the following code snippets didn't give the
> same result :
>
> ### Python ###
>
> liste = [1,2,3]
>
> def foo( my_list ):
>     my_list = []
>
> foo(liste)
>
> print liste# she expected liste to be an empty list
>
> ### Perl ###
>
> @lst =(1,2,3);
> $liste =\@lst;
> foo($liste);
> print "@lst\n";
>
> sub foo {
>  my($my_list)=@_;
>  @{$my_list}=()
>
> }
>
> I have to admit that I don't know how to clearly explain to her the
> differences between these results.
> Could someone please help us understand these difference between
> Python and Perl ?
>

David Ullrich gives a great and complete answer. I want to focus on
some of the subtleties.

Perl and C share a lot in common. There are "direct" variables, things
like numbers and arrays. These aren't references to object, but the
object is itself stored in the variable. That is, you can't talk about
the thing that is '@lst' without creating a reference to it.

Python, on the other hand, doesn't have direct variables. Well, it
does, it is just that all of the direct variables are really pointers
or references to the values they reference.

Imagine a perl where you are only allowed to use scalars, and
specifically, scalars that are references to object but not references
to references. That is the Python variable system.

To be more concrete...

This statement cannot be expressed in Python:

 @lst = (1, 2, 3);    # perl


However, you can create an arrayref (perl) / list (Python) and assign
a scalar (perl) / variable (Python) to reference it:

 $liste = [1, 2, 3];  # perl
 liste = [1, 2, 3]    # Python


Likewise, this statement cannot be expressed in Python:

 $refref = \$ref;     # perl


Although you can cheat in both perl and Python to get a similar
result:

 $refref = [$ref]     # perl
 refref = [ref]       # python


As far as the functions, the Python version and the perl version are
doing two completely different things. David explains how to write a
Python version that does what the perl version is doing. If you wanted
a perl version that did what your python version did, it would look
like this:

 sub foo {
   my ($my_list) =  @_;
   $my_list = [];
   return undef;
 }


Is Python's variable system better than perl's? It depends on which
way you prefer. As for me, being a long-time veteran of perl and
Python, I don't think having a complicated variable system such as
perl's adds anything to the language. Python's simplicity in this
regard is not only sufficient, but preferable.



More information about the Python-list mailing list