Anda di halaman 1dari 21

Perl and Python Rishabh Lala

The following table is the code comparison for same functionalities (mostly) in both
programs. At the end of the table, opinionative conclusion is presented.

Problem Statement: Text Editing Functionality in Python in comparison to Perl


1) Writing/reading the contents of one text file to another.
2) Formatting data of the text file.
3) Performing basic mathematics with the data obtained.
4) Renaming file, creating a file that takes in arguments from another file.

Parameters Python Perl

Commenting # #

Extension .py .pl

Double vs Single Quotes Same Not Same, single quotes


dont consider \n to input
new line

Semicolon Not required Required to terminate

(escape sequence) print "trying to use


Using Double quotes escape sequence\"one\
in perl";

\a n/a Error sound

\u n/a Adjoining character case


capatalized (upper
cased)

\l n/a Adjoining character case


lowered

\L n/a All following characters


lowered

\U n/a All following characters


uppered

\Q n/a All words are followed by


backslash (\)

(Scalar variable) No pre-sign required. Defined using $ sign


Float, character, integer

Octal number oct(any number) Begins with 0

Hexadecimal hex(any character) Begins with 0x, example


$variable_name = 0xa;
(Array) X = [] Array Definition Defined using @
Float, character, integer X = [A, B, 3] @X=(A,B,3);

Non array string object can


be accessed as array:
X = AB3 Python
automatically puts the letters in
single array cells

Array Definition name=[anything,,,..] @name=(anything,,,..)

Tuples and List x =(1,2,3,4,"R") -> tuple are very Only arrays exist
efficient in terms of memory but
they cannot be appended or
edited like the array.

Tuple operations:
tuplename =(,,,,)
len(tuplename)
max(tuplename)
min(tuplename)

If editing is required, list is


preferred. The following list
operations can be performed:

len(listname)
max(listname)
min(llistname)
listname.count()
To count occupied cells in the
list
listname.append(anything)
listname.remove(cellnumber)
listname.sort()

Variable Argument #VARIABLE ARGUMENTS N/a


Function
def variable(*argument):
for var_ in argument:
print(var_)
return
variable(1,3,45,'hi')
Asterisk sign denotes
variable arguments, stored as
tuple

Anonymous Function multiply=lambda v1,v2:v1*v2 N/a


print("Result",multiply(10,20))
Easy to use and simple to
define functions
lambda is keyword to denote
anonymous function

Array Indexing array_name[0] Example:


@array_name[0]

Array Operations X.append(4) -> Add to the array push(@X,word) -> similar
at the last location to append
unshift(@X,word) -> add
word in the beginning
X.insert(1, Hi) -> add to
defined location pop(@X) -> delete last cell
unshift(@X) -> delete first
X.pop(2) -> pop keyword cell
deletes from an array from
specified location $size_of_array=@array_n
ame
len(arrayname)
Splice(@X,1,2,@new_wor
d,new_word) -> splice
X.split() means replace

$glued=
join("",@array_name); ->
changing array to string

$var_a ="\n trying to use


escape sequence\Q In
perl\n";

@array_from_string =
split('Arrayfromstringis',$
var_a);

@alphabetically_sorted_
array= sort(array_name);

@merged_array=(@array
1,@array2)
Dictionary Function capitals={'one':'washington DC', %capital =
'two':'Ottawa'} %capitals=("one"=>"was
hington DC", "two"=>
new={'three':'London'} "Ottawa");
print ("$capitals{'one'}");

capitals.update(new) @ranks=keys(%capitals);
print("Keys @ranks")
print (capitals)
@ranks=values(%capital
->{'one': 'washington DC', 'two': s);
'Ottawa', 'three': 'London'} print("values @ranks")

Other dictionary functions $size =keys (%capitals);


capitals.values() print("Keys size is $size
capitals.keys() \n");
-> size of keys

$size =values
(%capitals); -> size of
values

$capitals{three}=("New
Delhi");
delete$capitals{three};

If statement Indent sensitive Indent Sensitive

if x%2==0: If (x%2==0)
print ("text", my_name) {
Print (even
number);
No braces are required, only
}
indent is sufficient Curved braces are required

Elseif if condition: if
{
elif condition: }
Eseif
else: {
}

Elseif
{
}

Unless Opposite of if statement


i.e. execute the block
when condition is not
true

else can be used with it


normally

Conditional statements sum=17 $sum=17;


if sum%2==0: $variable=($sum%2==0)?
print("Even No.") "The number is
else: even":"Number is odd";
print("Odd No.") print "$variable\n";

While statement For loop is preferred for most $x=1;


purposes. while ($x<10)
Similarly Until loop can be However, while loop works as {
made, which fails until the usual. print ("$x");
condition is satisfied. $x=$x+1;
}

For statement for x in range(30): for($x=1;$x<=20;$x=$x+1


print(x) )
for x in range(10,30,2): {
print ("$x");
print(x)
}
Or using array
@X=(1..100) or
@X =(a..z)

Accessing element of array For var_name in number: foreach $var(@number)


one at a time print (var_name) {
print("$var \n");
}

Do While Not so much used $x = 1;


do
{
print ("Hi \n");
$x=$x+1;
}while $x<10;

Nested For NESTED LOOP EXAMPLE $b=5;


(to find prime numbers till $c=1;
100) for
(indent is important) ($a=1;$a<=$b;$c=$c+1)
{
for var1 in range (2,101):
flag=True for($f=1;$f<=$c;$f
for var2 in range(2,var1-1): =$f+1)
if(var1%var2==0): {
print(var1,"is not a prime print("*");
number") }
flag=False print ("\n");
$a=$a+1;
break
}

if flag==1:
print(var1, " is a prime
number")

Double Quotes vs single Doesn't matter Matter


quotes

Get out of Loop for next continue next is like continue


iteration, ignoring the statement, pushes the
subsequent commands program counter to the
next loop.

last break Similar to next


statement.On execution,
pushes the program
counter out of the larger
loop so no more
iterations.

redo redo statement executes


the outer loop again,
irrespective of the failure
of the condition
statement.

Power operation ** instead of ^

Not equal to not a==b !=

String comparison if (A ge B)
operators: {
print ("Yes");
}

else
{
print ("No");
}

ge= greater than or equal


to
le=lesser than or equal to
gt =greater than
lt=lower than
eq =equal to
Ne = not equal to
Note: letters in the
sequence are assigned
values, ex. A<Z.

Shorthand assignment Same as in perl $y+=5 -> $y=$y+5


operators Example: Similarly -, *, /, %, and **
c+= is c=c+variable can be used

High level operations 5+4*2 print(5+4*2);


Output is directly displayed Print and semi-colon are
required to see output

Binary operators bin(any number & any number) %b$x <- converts x
Using format specifier %b. value into binary
Binary Operations &|^ &,|,^,~ and, or, exclusive
or(xor) and 32 bit
complement

Logical Operators and and


or or
not not
Note: all these generally
used with if condition

Find operation water in waterbottle No such operator


-> True

is same as operation a=42 No such operation


b=42
c=42 -> character
a is b
-> True
a is c
-> False

is not also works

Misc. Operators $var="NoText\n";


print($var x 20);
Var++ -> Print then
incremprint(abs(-
6))print(abs(-6))ent
++Var -> increment then
print

Mathematical Functions abs(-6) print(abs(-6))

Advanced math library in Import math print(sqrt(16)


python -> 4
Examples:
math.ceil(35.8)
-> 36

Math.e
-> 2.718281828459045

math.exp(any number)
-> for exponential

math.floor(16.94)
->16

math.sqrt(16)
-> 4

math.log(math.e)
-> 1

math.log10(2)
-> log10 to the base 2

max(,,,,,)
min(,,,,,)
round(19.923432,2)
->19.92

math.modf(12.123)
->(0.12299999999999933,
12.0)
Separates the decimal from
the whole number.
math.pow(4,2)
->16
4^2

math.hypot(5,12)
->13

math.pi
->3.141592653589793

math.degrees(1)
->57.29577951308232
Converts to radians

Date Time Function Import time as t $datetime=localtime();


t.asctime() print ("$datetime");

In array format
->'Tue Aug 15 01:08:43 2017'
@datetime=localtime();
print ("@datetime[0]");
import calendar
print(calendar.month(1965,3)) Seconds, minutes, hours,
day, month, year, week
->prints the full month calendar
in the shell

Passing value to the def rectangle(length,breadth): sub rectangle


subroutines area=length*breadth {
print(area) $length=@_[0];
$breadth=@_[1];
$area=$length*$br
rectangle(10,20) eadth;
print"the area is
$area \n";
}

rectangle(10,20);

Using ASCII char=input() sub charworks


characterization to classify if ord(char)>=65 and {
the characters. ord(char)<=90: foreach $c(@_)
{
print('UpperCase')
if
if char in ('A','E','I','O','U'): (ord($c)>=65 and
print('Upper case vowel') ord($c)<=90)
else: {
print('consonent')
elif ord(char)>=97 and push(@upper, $c)
}
ord(char)<=122:
print('lower case') elsif(ord($c)>=97
if char in ('a','e','i','o','u'): and ord($c)<=122)
print('lower case vowel') {
else:
print("no alphabet entered") push(@lower, $c)
}

elsif(ord($c)>=48
User input can be taken and ord($c)<=57)
through {

push(@digits, $c)
}
else
{

push(@special,
$c)
}
}

print("Upper Case
@upper\n");
print("Lower Case
@lower\n");
print("Special
Case @special\n");
print("Digit Case
@digits\n");
}

charworks('a','b','B','D','#'
,'1','(','7');

User Input command var_name=input() $var_name=


<STDIN>;

Create variable directly count =0 $ or @ is required


during loop without format print("Enter your name")
specifier name=input()
for newvar in name:
if (newvar in
('a','e','i','o','u','A','E','I','O','U')):
count=count+1

print("Number of vowels:",
count," ")

Local variable vs Global All defined variable in the block All defined variables
variable are local by default, global are global by default,
keyword is required to define so they require
global variable keyword my to be
defined as local

Argument and Block def foo (arg1,arg2,...): sub foo {


Definition ...do stuff... my $arg1 = shift;
my @rest_of_args = @_;
...do stuff... }

Note: To know the number of arguments passed to the subroutine, the array can be
saved as $.
Arrays can also be passed to the subroutines using @ symbole.
my keyword makes the variable private to the subroutine.

Return Statement #RETURN STATEMENT

sub circle
{
return
3.14*@_[0]*@_[0];
}

$area=circle(11);
print ("$area");

Opening Text File myfile=open("C:\\Users\\Rishab use strict;


h\\Documents\\new.txt","w") use warnings;
open(NEWFILE,
"C:/Users/Rishabh/Docum
myfile.write("Hi, I just created a
ents/new.txt");
file using python")
print ("outside the loop");
myfile.close()
while(<NEWFILE>)
{
print ("inside the
loop\n");
print("$_");
}
close (NEWFILE);

Input from User input() <STDIN>

Rename os.rename(C:\\Users\\Rishabh\\ rename("C:/Users/Rishabh


Documents\\new.txt,"C:\\Users\ /Documents/new.txt","C:/U
\Rishabh\\Documents\\newnam sers/Rishabh/Documents/n
ewname.txt"))
e.txt")

mkdir(new folder location


with name)

Remove os.remove(C:\\Users\\Rishabh\\
Documents\\new.txt)

Append Text myfile=open("C:\\Users\\Rishab


h\\Documents\\new.txt","a")

myfile.write("Hi, I just created a


file using python")

myfile.close()

Read contents from text file myfile=open("C:\\Users\\Rishab


h\\Documents\\new.txt","r")

myfile.read() <- the arguments


specifies the no. of characters
to read

myfile.close()

Convert text lines to list myfile=open("C:\\Users\\Rishab


h\\Documents\\new.txt","r")

myfile.readlines() <-specify the


number of lines to be read

myfile.close()

Writing contents line by Just use \n


line.
Modify contents of a line myfile=open("C:\\Users\\Rishab
h\\Documents\\new.txt","r")

array_variable=myfile.readlines(
)

array_variable[2]=this 2 refers
to third line as array starts at 0th
place\n

myfile=open("C:\\Users\\Rishab
h\\Documents\\new.txt","w")

myfile.writelines(array_variable)

myfile.close

len(sys.argv) $#ARGV+1

def foo (arg1,arg2,...): shift(@ARGV)


...do stuff... This shifts one argument to
the command line.

Count a word in text stringname.count(anyword)

Check the ending of a line stringname.endwith(anyword


)

->False/True

Find word in text stringname.find(anyword)

Change case of opening stringname.capatalize()


letter of sentence

Check if the string is in stringname.isupper()


upper/lower case
stringname.islower()

->True/False
Other Text Functions len(stringname)

Character length of the


string

stringname.lower()

stringname.upper()

stringname.title()

stringname.swapcase()

To change case like MS


word

stringname.lstrip(anyletter)

To strip(remove) any letter


from the beginning

stringname.rstrip(anyletter)

To strip(remove) any
letter(s) from the end

stringname.strip(anyletter)

To strip(remove) any
letter(s) from the beginning
and end

string.replace(anyword,with
anyword)

Replace any word from the


string with new word.
Managing Directories import os

os.mkdir("C:\\Dr.Consolazio\\
Learnings\\Python\\newdirect
ory1")

os.chdir("C:\\Dr.Consolazio\\L
earnings\\Python\\newdirecto
ry1")

os.mkdir("NewFolderInside")

os.rmdir(NewFolderInside)

Opinion: Python can be regarded as High Level Perl.


Reason: Python has the following mentioned advantages over Perl :
1) High level of coding: semicolon, loop parenthesis, variable initializers are not
required. This reduces chances of syntax errors as programing is much clear
and consize. Therefore, Python saves programing time.
2) More advanced functions: range, len, function definition, function names; all
involve high level operations.
3) Functions like tuple and list make python advantageous as they bring faster
speed to processing as compared to conventional arrays.
4) Python has high level functions to develop windows applications, example
calculator.
5) Python with combination of Javascript can be used for web development
applications
Conclusions: Python is better syntax and capability wise.
Appendix: Other Python Programs
Array Definition:
my_name = "Rishabh Lala"

Conditional Statement using array


if my_name[0].lower()=="r":
print("Hi")

Elif command and concatenations


if my_name[0].lower()=="a":
print ("Last letter of my name is", my_name)
elif my_name[0].lower()=="l":
print ("The elif command executed",my_name + " Hi")

% Easy concatenations
% comma to separate characters contained in array

Combine strings with characters


X = 12
Y = text
Z = str(X)+Y
% Each statement executes whenever entered. Its like command window of MATLAB, but with
a difference: doesnt prints when unintended. No semi-colon is required.
% variables are just redefined and do not carry any previous data

Its like C++


K = "text %d" %X
K = "text %.3f" %X
% limit the float to three decimal places, it rounds it to specified decimal places.
\n -> within the double quotes(while using string) creates a new line in text
\t -> tab function

Other Important Keywords:


In
Ham in Hamburger -> returns true or false depending Ham is in Hamburger or now.

X = [] -> Array definition


X = [A, B, 3]
X.append(4) -> Add to the array at the last location
X.insert(1, Hi)
X.pop(2) -> pop keyword deletes from an array

len("words") -> count the number of letters in the double quotes


x =(1,2,3,4,"R") -> tuple are very efficient in terms of memory but they cannot be appended or
edited like the array.
name["abc"] = "DEF" -> Dictionary Functionality
name ["DEF"] = "IJK" +str(10) -> Dictionary Functionality
name[DEF] -> retrieve items from dictionary
name.keys() -> lists (array) all the keys whose meaning are defined in the specific dictionary
name.values() -> array of all defined values (meanings)

>>> name
{'abc': 'DEF', 'DEF': 'IJK10'}

del name["abc"] -> delete article from dictionary

"Ham ham".upper() -> change cases


'HAM HAM'

>>> "Super Baby".lower() -> lower the case


'super baby'

b = "I am ham"
b.split()
['I', 'am', 'ham'] -> forming an array using the words in the sentence

Join array with strings


b = "Rishabh Lala is here"
c = ["a", "b", "c", "D"]
b.join(c)
'aRishabh Lala is herebRishabh Lala is herecRishabh Lala is hereD'

L = [1,2,3,4,5]
Commands associated:
L[:] -> list all in the array
L[::2] -> alternate number array
L[1:] -> skip first cell and rest remains in array
L[1::2] -> skip first cell and write every second cell in new array

Array in Array (nested array)


L = [1,2,3]
G = [L,4,5,6]
>>> G
[[1, 2, 3], 4, 5, 6]

set(array name) -> arranges the variables in the ascending order


Conditional statements
if 10>9 and 5<6:
print ("two conditions satisfied")

Output: two conditions satisfied

% and is a keyword

Not equal to keyword


if not 5==10:
print("5 is not equal to 10")
else:
print ("5 is equal to 10")

5 is not equal to 10

% not is a keyword

For loop combined with range keyword


for x in range(30):
print(x)
for x in range(10,30,2):
print(x)

Continue -> when used in for loop -> spits all other values when the for loop is invalid.

Define multiple variables in a go


a,b = 1,2

Easy way to print Fibonacci series


a,b = 1,2
>>> while (b<100):
fiboSeq.append(a)
a,b = b,a+b
print (fiboSeq)

Factorial
factorial =0
>>> for i in range (30):
factorial +=i
print (factorial)
% += increments and adds the same number

EASY DEBUGGING
Try and Except Keyword

try:
x = 5+ ham
except:
5+10

15

% try this syntax, if that doesnt work, execute the except code

Pass
>>> try:
5+ 5
except:
pass
%just add try before the doubtful code and pass to just outrageously move on

Raise
raise TypeError("just spitout this error")
% raise an error of your choice

Try Except Finally


try:
x = 5+ham
except ZeroDivisionError:
print ('will not see this')
finally:
print ("the final word")
% Finally is used to do any last things

Function

def fun():
print('function ran')

>>> x = fun()
function ran
dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__',
'__spec__', 'a', 'b', 'factoria', 'factorial', 'fiboSeq', 'fun', 'i', 'j', 'primes', 'x']

%all variables created in the file so far

Calling by reference
def addition(x,y):
z=x+y
return z

>>> addition(10,20)
30

def addition(x,y):
'"document"'
z=x+y
return z
%documenting the purpose of function while defining the function
Writing a text file
import time as t
from os import path

def createFile(dest):
'" The script creates a text file at the passed location and names file to date"'
## File name = month_Day_year
date = t.localtime(t.time())
name = "%d_%d_%d.txt" %(date[1],date[2],(date[0]%100))
if not (path.isfile(dest+name)):
f = open(dest+name,"w")
f.write("\n"*30)
f.close()

if __name__=='__main__':
destination='C:\\Dr.Consolazio\\Learnings\\Python\\'
createFile(destination)
input("Done!!")

#easy import and import aliasing. Time and date are contained in the time file.
open(filename, w or r or a) -> write or read or append the text file. By default it is set to read
the file.

Anda mungkin juga menyukai