Difference between revisions of "Python-Perl cheatsheet"

(Cheatsheet: pickle vs storable)
 
(33 intermediate revisions by the same user not shown)
Line 8: Line 8:
  
 
-->
 
-->
 +
 +
==Cheatsheet==
 +
This is so far based on my study of ''Learning Perl'' (O'Reilly), also known as "the llama book", plus stuff I found on the web.
  
 
See also [http://wiki.python.org/moin/PerlPhrasebook the Perl Phrasebook] on wiki.python.org
 
See also [http://wiki.python.org/moin/PerlPhrasebook the Perl Phrasebook] on wiki.python.org
Line 29: Line 32:
 
|
 
|
 
| if x == y
 
| if x == y
| if ( $x == $y ) ''or'' if ( $x eq $y)  
+
| if ( $x == $y ) '''and''' if ( $x eq $y)  
 
| Perl requires parenthesis in a comparison (same for '''while'''). Perl uses ''different'' comparators for numbers and strings
 
| Perl requires parenthesis in a comparison (same for '''while'''). Perl uses ''different'' comparators for numbers and strings
 
|-
 
|-
Line 58: Line 61:
 
|($fred, $barney, $dino) = ("flintstone", "rubble", undef);
 
|($fred, $barney, $dino) = ("flintstone", "rubble", undef);
 
|
 
|
 +
|-
 +
|pretty-print array
 +
|print array
 +
|print "@array\n";
 +
|Simply using ''print @array'' will print the contents but without spacing, so that (1,2,3) becomes 123.
 
|-
 
|-
 
| array concatenation
 
| array concatenation
Line 83: Line 91:
 
|@list = reverse @list;
 
|@list = reverse @list;
 
|Python is in place, Perl is not. Same for sort.
 
|Python is in place, Perl is not. Same for sort.
 +
|-
 +
| Check if item in list
 +
| if item in list :...
 +
| if ( grep {$_ eq $element} @array ) { ...
 +
| TIMTOWDI; see also using hashes and exists()
 +
|-
 +
| Index of item
 +
| list.index(item)
 +
| my( $index )= grep { $array[$_] eq $search_for } 0..$#array;
 +
| See [http://www.perlmonks.org/?node_id=75660 Perlmonks.org]
 +
|-
 +
|colspan=4|<span style="color:#909000">'''Mappings (dictionaries / hashes)'''<span style="color:#900000">
 +
|-
 +
| Define hash
 +
| dict = { 'a':1 , 'b':2 }
 +
| hash = ( 'a'=> 1, 'b'=> 2, )
 +
|
 +
|-
 +
| Retrieve value
 +
| dict[key]
 +
| $hash{$key}
 +
|
 +
|-
 +
| Invert a hash
 +
| inverted_dict = dict([[v,k] for k,v in mydict.items()])
 +
| %inverted_hash = reverse %hash;
 +
|
 +
|-
 +
| Keys
 +
| keys = dict.keys()
 +
| @keys = keys %hash;
 +
|
 +
|-
 +
| Values
 +
| vals = dict.values()
 +
| @vals = values %hash;
 +
|
 +
|-
 +
| Iterating a hash
 +
| for key in dict.keys(): dict[key]...
 +
| while ( ($key, $val) = each %hash) {...}
 +
| Notice the '''each''' function -iterates and the assigment is false when there are no more couples. Notice also, if you want keys sorted, you can use foreach $key (sort keys %hash) {...} , which is similar to the Python case.
 +
|-
 +
| Creating an hash from two arrays
 +
| for key,val in zip(keys,vals): dict[key]=val
 +
| @dict{@keys} = @vals
 +
| See hash slicing.
 +
|-
 +
|colspan=4|<span style="color:#900000">'''Functions and subroutines'''<span style="color:#900000">
 +
|-
 +
| Subroutine/function declaration
 +
| def function(): ...
 +
| sub function { ... }
 +
|
 +
|-
 +
|
 +
| return x
 +
| return x '''or''' ''[last evaluated expression is return value]''
 +
| Perl has an explicit return statement, but it's facultative. A return-less sub won't return "undef", but the last expression evaluated!
 +
|-
 +
| Arguments of a function
 +
| def function(arg1,arg2...)
 +
| sub function { ... $_[0] , $[1] ... }
 +
| Perl doesn't have explicit arguments; args are stored in the @_ default array.
 +
|-
 +
| Name of argument variables
 +
| def function(arg1,arg2...)
 +
| sub function {  my($arg1, $arg2) = @_; }
 +
| You can name arguments by declaring them using the @_ default array
 +
|-
 +
| Static variables in function scope
 +
| ''(define a generator ; see ''yield'' ) ; (use namespace within function, like ''def foo(): foo.myvar=1'')''
 +
| state $myvar=1;
 +
| Defines a variable which is statically defined but within function namespace -so it's not resetted when function is called, it maintains its state.
 +
|-
 +
| Returning more than one array/dictionary
 +
| return a,b
 +
| return \@array, \%hash;
 +
| In Perl, functions collapse all input in a single array and all output in a single array. You have to play with references.
 +
|-
 +
|colspan=4|<span style="color:#900090">'''Input / output'''<span style="color:#900000">
 +
|-
 +
|
 +
| x = raw_input()
 +
| $x = <STDIN>;
 +
| Interestingly if you use a list context, like in @x = <STDIN> , you get multiline stdin input.
 +
|-
 +
|
 +
| sys.argv
 +
| @ARGV
 +
|
 +
|-
 +
| Program's own name
 +
| sys.argv[0]
 +
| $0
 +
|
 +
|-
 +
| Multiple file arguments stream
 +
| ''see '''[http://docs.python.org/library/fileinput.html fileinput]''' module''
 +
| <>
 +
| Comntains sequentially all the file stream from all files in program arguments, like ./script.pl file1 file2 file3
 +
|-
 +
| Open a file stream for reading
 +
| f = open('test.txt')
 +
| open TEST, "test.txt";
 +
| Use uppercase, it's good practice.
 +
|-
 +
| Open a file stream for writing
 +
| f = open('test.txt','w')
 +
| open TEST, ">test.txt";
 +
|
 +
|-
 +
| Open a file stream for appending
 +
| f = open('test.txt','a')
 +
| open TEST, ">>test.txt";
 +
|
 +
|-
 +
| Close file
 +
| f.close()
 +
| close TEST;
 +
|
 +
|-
 +
|colspan=4|<span style="color:#000060">'''Error handling'''<span style="color:#900000">
 +
|-
 +
| Raise exception
 +
| raise
 +
| die
 +
|
 +
|-
 +
| Catch exception
 +
| try: ... except: ...
 +
| eval { ... } or do {...}
 +
|
 +
|-
 +
|colspan=4|<span style="color:#000060">'''Operating system interaction'''<span style="color:#900000">
 +
|-
 +
|Environment variables
 +
|os.environ
 +
|%ENV
 +
|-
 +
|colspan=4|<span style="color:#600060">'''Miscellaneous'''<span style="color:#900000">
 +
|-
 +
|Save data structures to disk
 +
|'''pickle''' module
 +
|'''Storable''' module
 +
|Perl has a quite long list of modules to save data structures to disk
 
|-
 
|-
 
|}
 
|}
 +
 +
==Traps==
 +
 +
===Static arrays===
 +
:To have a valid
 +
:<code>state @array</code>
 +
:you need to
 +
:<code>use 5.010;</code>
 +
 +
===while/foreach memory consumption===
 +
 +
:This:
 +
:<code>while (<STDIN>) { ...</code>
 +
 +
:reads one line at a time.
 +
:This:
 +
:<code>foreach (<STDIN>) { ...</code>
 +
:instead loads all STDIN into memory before processing it!
  
 
[[Category:Programming]]
 
[[Category:Programming]]
 +
 +
===Print a hash===
 +
*If you do
 +
:<code>print "%hash";</code>
 +
:it will NOT interpolate and write the hash! it will dumbly write the string "%hash".
 +
:You can unwind the array by <code>@unwind_hash = %hash</code> (but it is difficult to read) or you have to write your helper function.

Latest revision as of 08:42, 9 August 2011


Cheatsheet

This is so far based on my study of Learning Perl (O'Reilly), also known as "the llama book", plus stuff I found on the web.

See also the Perl Phrasebook on wiki.python.org

what Python Perl notes
null type None undef not exactly identical
String concatenation "py"+"thon" "pe"."rl"
if x == y if ( $x == $y ) and if ( $x eq $y) Perl requires parenthesis in a comparison (same for while). Perl uses different comparators for numbers and strings
Arrays
declare a list [1,2,3] (1,2,3) note that arrays contain only scalars! (1,2, (3,4), 5) becomes (1,2,3,4,5)
array length len(array) $#array + 1 Python returns the length of array. Perl gives me the index of the last element. Also, the array value in a scalar context is (usually) its size.
range(1,100) (1..100)
create a list from whitespaced values "fred barney wilma dino".split() qw( fred barney wilma dino); You can use separators others than parenthesis, e.g. qw ! fred barney wilma dino !
multiple assignment fred, barney, dino = "flintstone", "rubble", None ($fred, $barney, $dino) = ("flintstone", "rubble", undef);
pretty-print array print array print "@array\n"; Simply using print @array will print the contents but without spacing, so that (1,2,3) becomes 123.
array concatenation a+b (@a, @b) you can also mix like (@a, 3, @b, undef)
array.append(item) push @array, item; See also Perl's unshift() for attaching to the front of array
val = array.pop() val = pop @array; See also Perl's shift() for removing from the front of array
List iteration for item in array foreach $item (@array) Note that $item is the real element of @array, so if you modify $item, you modify the array content
list.reverse() @list = reverse @list; Python is in place, Perl is not. Same for sort.
Check if item in list if item in list :... if ( grep {$_ eq $element} @array ) { ... TIMTOWDI; see also using hashes and exists()
Index of item list.index(item) my( $index )= grep { $array[$_] eq $search_for } 0..$#array; See Perlmonks.org
Mappings (dictionaries / hashes)
Define hash dict = { 'a':1 , 'b':2 } hash = ( 'a'=> 1, 'b'=> 2, )
Retrieve value dict[key] $hash{$key}
Invert a hash inverted_dict = dict([[v,k] for k,v in mydict.items()])  %inverted_hash = reverse %hash;
Keys keys = dict.keys() @keys = keys %hash;
Values vals = dict.values() @vals = values %hash;
Iterating a hash for key in dict.keys(): dict[key]... while ( ($key, $val) = each %hash) {...} Notice the each function -iterates and the assigment is false when there are no more couples. Notice also, if you want keys sorted, you can use foreach $key (sort keys %hash) {...} , which is similar to the Python case.
Creating an hash from two arrays for key,val in zip(keys,vals): dict[key]=val @dict{@keys} = @vals See hash slicing.
Functions and subroutines
Subroutine/function declaration def function(): ... sub function { ... }
return x return x or [last evaluated expression is return value] Perl has an explicit return statement, but it's facultative. A return-less sub won't return "undef", but the last expression evaluated!
Arguments of a function def function(arg1,arg2...) sub function { ... $_[0] , $[1] ... } Perl doesn't have explicit arguments; args are stored in the @_ default array.
Name of argument variables def function(arg1,arg2...) sub function { my($arg1, $arg2) = @_; } You can name arguments by declaring them using the @_ default array
Static variables in function scope (define a generator ; see yield ) ; (use namespace within function, like def foo(): foo.myvar=1) state $myvar=1; Defines a variable which is statically defined but within function namespace -so it's not resetted when function is called, it maintains its state.
Returning more than one array/dictionary return a,b return \@array, \%hash; In Perl, functions collapse all input in a single array and all output in a single array. You have to play with references.
Input / output
x = raw_input() $x = <STDIN>; Interestingly if you use a list context, like in @x = <STDIN> , you get multiline stdin input.
sys.argv @ARGV
Program's own name sys.argv[0] $0
Multiple file arguments stream see fileinput module <> Comntains sequentially all the file stream from all files in program arguments, like ./script.pl file1 file2 file3
Open a file stream for reading f = open('test.txt') open TEST, "test.txt"; Use uppercase, it's good practice.
Open a file stream for writing f = open('test.txt','w') open TEST, ">test.txt";
Open a file stream for appending f = open('test.txt','a') open TEST, ">>test.txt";
Close file f.close() close TEST;
Error handling
Raise exception raise die
Catch exception try: ... except: ... eval { ... } or do {...}
Operating system interaction
Environment variables os.environ %ENV
Miscellaneous
Save data structures to disk pickle module Storable module Perl has a quite long list of modules to save data structures to disk

Traps

Static arrays

To have a valid
state @array
you need to
use 5.010;

while/foreach memory consumption

This:
while (<STDIN>) { ...
reads one line at a time.
This:
foreach (<STDIN>) { ...
instead loads all STDIN into memory before processing it!

Print a hash

  • If you do
print "%hash";
it will NOT interpolate and write the hash! it will dumbly write the string "%hash".
You can unwind the array by @unwind_hash = %hash (but it is difficult to read) or you have to write your helper function.