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

Nigel Rantor wiggly at wiggly.org
Tue Aug 12 12:46:14 EDT 2008


Palindrom wrote:
> ### Python ###
> 
> liste = [1,2,3]
> 
> def foo( my_list ):
>     my_list = []

The above points the my_list reference at a different object. In this 
case a newly created list. It does not modify the liste object, it 
points my_list to a completely different object.

> ### Perl ###
> 
> @lst =(1,2,3);
> $liste =\@lst;
> foo($liste);
> print "@lst\n";
> 
> sub foo {
>  my($my_list)=@_;
>  @{$my_list}=()
> }

The above code *de-references* $my_list and assigns an empty list to its 
referant (@lst).

The two code examples are not equivalent.

An equivalent perl example would be as follows:

### Perl ###

@lst =(1,2,3);
$liste =\@lst;
foo($liste);
print "@lst\n";

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

The above code does just what the python code does. It assigns a newly 
created list object to the $my_list reference. Any changes to this now 
have no effect on @lst because $my_list no longer points there.

   n



More information about the Python-list mailing list