Some similarities and differences between Perl and Python _ Other

Source: Internet
Author: User
Tags constructor data structures documentation function definition garbage collection numeric scalar in python
About the origins and characteristics of Perl and Python

Perl is the abbreviation of practical extraction and report Language, created by Larry Wall in 1987, originally designed to facilitate the processing of reports on UNIX, and has become a fully functional programming language after a long period of development, The current latest version for Perl5.14.1,perl as a free and powerful programming language, the central idea is: There ' more Than one Way to do It. (more than one way to do it), "tim toady". As a "glue-type" language, it has strong regular expression and pattern matching function as well as flexible data structure, such as dynamic array, Hash and so on, in the grammar rules for reference C + +, Basic, Pascal and other languages, the disadvantage is that there are some redundant syntax, code readability is poor.

Python is an object-oriented, analytic, interactive, open source programming language, originated in late 1989 by researchers at the CWI (Amsterdam National Institute of Mathematics and Computer science), Guido van Rossum, a public offering in early 1991, and its open-source distribution facilitated The rapid development of Python has now formed a powerful community force. The Python Developer's philosophy is "one way, preferably one way to do something". Python has the advantages of easy learning, code specification, simple syntax, portability, support multi-platform, and rich class library.

Both Perl and Python are open source, but their philosophy is just the opposite, so it is often compared between the two languages. The following chapters will be a simple comparison and identification of the two languages in terms of basic data types, control flow, functions, object-oriented, and text processing.

basic data types for Perl and Python

Scripting languages support a variety of data types, variables need not be stated beforehand, types are dynamically determined based on values, and a variable can store different types of values in the program depending on the context.

The basic data types that Perl supports include: scalar, array, hash. The definitions are expressed in $, @,%, respectively.

Scalar (scalar): Scalar is the simplest data type in Perl, and most scalars consist of numbers or strings. Where numeric types such as integers, floating-point numbers, and so on, the string has two forms of single and double quotes, there is no limit to length. The difference is that within a single quotation mark \ n does not represent a newline, but a backslash and N, the string within double quotes can be escaped by a backslash. The operator of the string has. concatenation operators and X repeat operators.

Array (Arrays): array with @ definition, such as my @array = ("A", "B", "C", "D"); Access the elements of the array with $array [1]. In Perl, arrays can also be treated as stacks, and the supported operators include POPs and PUSH,SHFT and unshift. The difference between the two sets of operations is that the former is processed at the tail of the array, while shift and unshift are processed for the head of the arrays. The pop gets the last element of the array, such as pop (@array) = d, and returns UNDEF if the array is empty. and Shift (@array) =a.

Hashes: Also known as associative arrays, are data structures that are accessed directly based on key code values (keys value). The% definition, such as%my_hash= ("Key1" => "," "Name" => "Zhang", "Age" => "24"), where the key is represented by a string, can be any size.

The hash-related functions are:

Keys: Returns a hash of the key list my @keylist = Keys%hash

Value: Return list of values my @valuelist = values%hash

Each: Returns a key-value pair with a list of two elements.

Copy Code code as follows:

while ($key, $value) = each%hash)
Print "$key => $value \ n";

Python supports five basic data types: Numbers (Numbers), strings (string), lists (list), tuples (Tuple), and dictionaries (Dictionary). where numbers and strings correspond to scalars in Perl, lists and arrays correspond, tuples can be viewed as immutable lists, dictionaries and hash correspondences.

Number (Numbers): Python supports five basic numeric types, int (signed integer), long (length integer), bool (Boolean), float (floating-point number), complex (plural).

String: Python also supports single and double quote strings like Perl, but unlike Perl, escape characters also work in single quotes. Python also supports a three-quote string that allows a string to span multiple lines, which can contain line breaks, tabs, and other special characters. Three-quote strings are often used to annotate or form documents. String support member operator In,not in, join operator + and repeat operator *. The Python string can be used as a list, supporting the slicing operator [],[:] and the reverse index. As follows:

such as astring= "ABCD", then the value of astring[0] is A,ASTRING[1:3]=BC, reverse index Astring[-1]=d

List: The list in Pyhon corresponds to an array in Perl. The definition of a list uses []. such as Li = ["A", "B", "Mpilgrim", "Z", "example"], support dynamic addition and deletion of elements as well as slicing operations.

Additional elements can be used Li.append ("test"), Li.insert (2, "new"), and Li.extend (["F", "GGF"])

Delete elements use Li.remove ("F") and Li.pop (). Note, however, that remove deletes only the first occurrence, and pops deletes the last element of the list and then returns the value of the deleted element.

Tuples (Tuple): Tuples and lists are very similar, but are represented by (), and tuples are immutable.

Dictionary (Dictionary): The dictionary, like the hash in Perl, defines a one-to-one relationship between key-value pairs, which can be arbitrarily named, and Python records its data type internally. Define a dictionary: d={"name": "Jon", "Family": "SH"}, the dictionary key is not repeatable, and case sensitive, while the dictionary elements are unordered. The dictionary also supports additions and deletions, adding elements to the dictionary d["age"]=23, deleting element del d[' name ', and deleting all elements if necessary to use D.clear (), or del D to delete the entire dictionary.

the control structure of Perl and Python

In terms of control results, Perl is richer than Python, in addition to supporting the traditional if, while, for control structure, but also supports until, unless, foreach, and so on, Python's control structure is relatively small, but has been able to meet the requirements of the language. This section makes a detailed comparison of these control structures.

IF Control Structure:

Both Perl and Python support the IF, If-else, If-else if-else three structures, which are essentially similar in syntax, but unlike Python, there is no Boolean type in Perl, 0 and Null represent False, the remainder represents True, and Everything else in Python is True except for ', ', 0, (), [], {}, None is False. At the same time Python represents block blocks directly with indents.

table 1. If Control structure

Perl Python
If if (expression) {
If expression:
If-else if (expression) {
If expression:
If-else If-else if (expression_a) {
} elseif (Expression_b) {
} else {
If expression1:
Elif expression2:

Perl also supports unless conditional control statements, the basic syntax is as follows:

Unless (expression) {
stmt_1; }

The difference between unless and if is that when the value of the conditional expression is false, the unless is followed by the Else statement. Such as:

Copy Code code as follows:

Unless ($mon =~/^feb/) {
Print "This month has at least thirty days.\n";
Print "Do you have what ' s going on here?\n";

loop control Structure:

For loop:

The For loop in Perl, in addition to supporting the traditional for loop, for (expression 1, expression 2, Expression 3), also supports a foreach statement with the basic syntax:

Copy Code code as follows:

foreach $i (@aList) {

Python does not support traditional for loops, but provides a powerful looping structure that traverses the sequence members while the For loop can follow the Else statement, the basic syntax is as follows:

For Inter_var in iterable:




While loop

The Perl loop control results also support the while and do-while as well as the until forms, until are similar to the while structure, except that unitl repeats when the condition is false. The until syntax is as follows:

Copy Code code as follows:

Until (expression)

Python only supports the while form, but Python can then follow the Else statement. The syntax is as follows:

While condition:




Loop control character

Perl has three loop-control operators, last, Next, Redo, respectively.

Last: Terminate the loop immediately, similar to the break in C. In a multi-layer loop, only the current loop block where last resides is valid;

Next: End the current iteration immediately;

Redo: Returns control to the top of this loop and does not go through the next iteration loop without a conditional test, but instead executes the loop block again. The biggest difference to next is that next will normally continue with the next iteration, and redo will perform the iteration again.

Python also has three loop control operators, which are break, continue, and pass statements.

Break: Similar to break in C;

The Continue:continue statement does not exit the loop structure, but immediately ends the loop, restarting the next round of loops, that is, skipping all statements after the continue statement in the loop body to continue the next round of loops;

Pass: The pass statement does not perform any action, usually as a placeholder or as a placeholder.

Perl and Python functions

Both Perl and Python support functions, passing parameters and calling functions in a program. The following compares the two in terms of function definition, invocation, return value, and parameter passing.

Table 2. A comparison of Perl and Python functions

Perl Python
  1. Basic syntax:
Sub functionname{
[Return value]
  1. Basic syntax:
    def functionname (arg1,arg2,[...]):
    [Return value]
  2. inline function:
    Python supports inline functions by defining functions within the definition body of an external function, but the entire function body is within the scope of the external function.
    Def outfun ():
    Def innerfun ():
    Print "Inner Fun Test"
    Print "Out Fun test"
return value Returns are displayed using the return statement, and the result of the last operation is returned by default if there is no return Returns are displayed using the return statement with no return statement and the default returns to None. If the function returns multiple objects, Python gathers them and returns in a tuple.
Call & Function Name (parameter 1, parameter 2, ...) If the declaration is in front, you can omit &. If the user defines a child procedure that has the same name as a built-in function, you cannot omit &.
The following example must be invoked using &chomp:
Sub chomp{
Print "It is my chomp\n";
  1. Use function name directly (parameter 1, parameter 2 ...)
  2. Function name (parameter name 1= value, parameter name 2= value ...)
function arguments
  1. After a subroutine call with a list expression enclosed by parentheses, all parameters are automatically stored in @_, where the first parameter is $_[0] and the second parameter is stored $_[1].
  2. Passing references, adding \ Representations as references before parameters
  1. Direct transmission According to the keyword order of the parameter Declaration;
  2. by keyword parameter testfun (par1= "2", par2= "45")
  3. Default parameters:
    > Python supports default parameters when passing parameters, and the rule is that all positional parameters must appear before any of the default parameters, such as
    def fun (arg1,defarg1= "var1", defarg2= "12"), if the parameter value is not given at the time of the call, the default value is used
  4. Variable length parameters:
    One way is to take advantage of non-keyword variable-length parameters, and the variable-length parameter tuples must be after the position and the default parameters, and the function syntax with tuples is as follows:
    def function_name ([formal_args,]*vargs_tuple):
    where * The shape arguments is passed as a tuple to the function.

    Another method is to use the keyword variable parameters, the difference is in the function of the parameter variable use * *.
    def dicvarargs (arg1,arg2= "Default", **therest):
    print ' Formal arg1: ', arg1
    print ' Formal arg2: ', arg2
    For Eachxtrarg in Therest.keys ():
    print ' Xtra arg%s:%s '% \ (Eachxtrarg, str (THEREST[EACHXTRARG])
Perl and Python packages and modules

The Perl program stores the names of variables and subroutines in the symbol table, and the collection of names in the Perl notation table is called the Perl package (package). The definition syntax is: package mypack; each symbol table has its own set of variables, subroutine names, and groups of names that are irrelevant, so you can use the same variable names in different Perl packages and represent different variables. There are two sources of Perl modules, one packaged with the Perl release and the other downloaded in CPAN. The concepts of Perl modules and packages are not clear, and they can sometimes be mixed. The operation of a module in a program is called an import module; the import module keyword uses; for example: use ModuleName; After the module is imported, the subroutines and variables can be used directly; To cancel a module that has already been imported, you can use the keyword no, such as: no modulename.

A. py file is a python module. Putting a bunch of related Python modules in a directory, plus a file, makes up a python package. Import modules in another Python program with import module or from module import * The difference is that import module imports all the identities in the module, but these identities are now in the modules name Word space. The From module import * Also imports all identities in the module, but the identities are placed in the current namespace.

Import a module or package to find the path in the following order:
1. Current directory

2. Environment variable Pythonpath directory list the installation directory of the 3.python interpreter

The OOP in Perl and Python

In Perl, a class is a Perl package that contains classes that provide object methods, and the method is a subroutine of Perl, whose first argument is a reference to a data item in a class. To create a new class in Perl, you first create a package with the extension. PM, the last one of the program must be "1;" When the Perl package is created. ; otherwise the package will not be processed by Perl.

Listing 1. Create Perl classes and objects

Copy Code code as follows:

Package person;
Use strict;
Sub New {
My $class = Shift ();
Print ("CLASS = $class \ n");
My $self = {};
$self->{"name"} = Shift ();
$self->{"sex"} = Shift ();
Bless $self, $class;
return $self;
where the new () method is the constructor of the object, the object instance that created the class must be called, and it returns a reference to the object. Combining a class name with a reference is called a "bless" object whose syntax is: Bless yereference [, classname]
Yereference is a reference to the "Blessed" object, classname is optional, specifies the package name of the object fetch method, and the default value is the current package name. You can also declare a constructor by using the function bless.
Sub New
my $class = shift;
My $self = {};
Bless $self, $class;
return $self;

Creating an object can use the New keyword directly. $object = new Person ("Mohand", "Sam", 345);

The methods in the Perl class, in the child functions of Perl, specify that the first parameter is an object or a referenced package, divided into static methods and virtual methods. A virtual method usually first shift the first argument to the variable self or this, and then use the value as a normal reference. One is through the object's reference (virtual method), and the first is to use the class name directly (static method). As in the previous example, if there is a getcontactlist in the class person, you can call the method directly using $object->getcontactlist ().

Perl supports overloading, and when two different classes contain the same method name, you can use:: operator to specify the method in which class to use.

$mess = Qava::grind ("Whole", "Lotta", "bags");

Qava::grind ($mess, "whole", "Lotta", "bags");

Perl uses a simple, reference-based garbage collection system. The number of links to the Perl trace object that is automatically destroyed when the last application of an object is released to the memory pool. Therefore, you generally do not need to define a destructor for the class.

Perl supports inheritance through array @ISA.

Package Employee;

Use person;

Use strict;

Our @ISA = QW (person); # inherits from

When a subclass inherits a parent class, all the methods of the parent class are inherited, but subclasses can also override methods of the parent class. If you join the Employee want to overwrite the getfirstname of the parent class:

Copy Code code as follows:

Package Employee;
Use person;
Use strict;
Our @ISA = QW (person); # inherits from
# Override Helper function
Sub Getfirstname {
My ($self) = @_;
# This is the child class function.
Print "This are Child class helper function\n";
return $self->{_firstname};

Call directly using $firstName = $object->getfirstname (); If you want to invoke the getfirstname of the parent class, you can use the $object->person::getfirstname ();

The basic syntax for creating a class in Python is:

Class ClassName (Bases):


The parameter base can be a single inheritance or multiple inherited parent class, object is the parent class of all classes, at the top of the class inheritance structure. The constructor for the class is __init__ (), where self is the first default parameter. The destructor of the class is __del__ (), and access to the methods and properties of the class can be used directly. accessor characters.

Python does not support pure virtual functions or abstract methods, and there is no essential difference between declarations and definitions. Properties of general or Python classes can be accessed via __dict__ or Dict (). Common properties are __name__, __doc__,__base__,__dict__. Create an instance of a class in Python without needing the key new, directly using the class name (). such as C=myclass ().

Python supports not only single inheritance and multiple inheritance, but also the overriding of methods.

Copy Code code as follows:

Class P (object):
def foo (self):
print ' Hi, I am p-foo () '
>>> p = P ()
>>> ()
Hi, I am P-foo ()

Now create class C, and inherit from P

Copy Code code as follows:

Class C (P):
def foo (self):
print ' Hi, I am c-foo () '
>>> C = C ()
>>> ()
Hi, I am C-foo ()

When the subclass is instantiated, the __init__ () method of the base class is not automatically invoked when __init__ () is derived from a class with a constructor __init () _. If you must call the base class's construction method, you can use the parent class name. __init__ (self) method or super (subclass name, self). __init__ (). Such as

Copy Code code as follows:

def __init__ (self):
Super (C, self). __init__ ()
print "Calling C ' constructor"

Python classes and instances support some built-in functions, such as

Issubclass (Sub,sup): Judge a class as a subclass of another class or a descendant class;

Isinstance (OBJ1,OBJ2): Determines whether an object is an instance of another given class;

a regular expression of Perl and Python
Regular expressions are a prominent feature of Perl, and there are three forms of Perl's regular Expressions:

Match: m/<regexp>/(can also be abbreviated as/<regexp>;/, omit m) Replacement: s/<pattern>/<replacement>/, for the simplification of the grammar with/< pattern>/<replacement>/says, omit s

Converting: tr/<charclass>/<substituteclass>/This form contains a series of characters-/<charclass>-and replaces them with <substituteclass >.

Table 3. Perl Common matching patterns

Grammar Description Sample
. Match all characters except line breaks B.C matched BAC
X? Match 0 times or one x string B?c match C or BC
x* Matches 0 or more x strings, but matches the least possible number of times B*c Match C or BBC
x+ Matches 1 or more x strings, but matches the least possible number of times B+c Match BC or BBC
.* Match any character 0 times or once B.*c Matching BGDC etc.
.+ Match any character that is 1 or more times B.+c Match BGC etc
{m} Matches the specified string that is just the M B{5}c Matching BBBBBC
{M,n} Matches the specified string below m above n b{1,2} match B or BB
{m,} Matches more than M-specified strings b{2, Match BB or BBB, etc.
[] Match characters within [] B[d]c Matching BDC
[^] Match characters that are not in accordance with [] B[^d]c matched BAc
[0-9] Match all numeric characters B[0-9]c Matching b1c
[A-z] Match all lowercase alphabetic characters B[a-z]c matched BAC
^ Characters that match the beginning of a character ^perl matches characters that begin with Perl
$ Characters that match the end of a character perl$ matches a character that ends in Perl
\d Matches a number of characters, as in [0-9] syntax B\DC Matching b1c
\d Non-digit, other same \d B\DC matched BAc
\w A string of English letters or numbers, as in [a-za-z0-9] syntax B\WC Matching b1c etc.
\w A string of non-English letters or numbers, as with [^a-za-z0-9] syntax B\WC Match b C
\s Spaces, as with [\n\t\r\f] syntax B\SC Match b C
\s Non-whitespace, as with [^\n\t\r\f] syntax B\sc matched BAC etc
\b Match a string with an English letter and number as a boundary \bbc\b matches BC but does not match BCA
\b Matches a string that does not have an English letter and a value as a boundary Sa\b will match strings such as sand and Sally, and not match Melissa.
A|b|c Match a string with a character or a B or C character
ABC matches a string containing ABC
Match A or B or C, etc.
(pattern) () This symbol will remember the string you are looking for, which is a very useful syntax. The string found in the first () becomes either a variable or a \1 variable, and the string found in the second () becomes a $ $ or \2 variable, and so on. B (\d) C means that any number matched will be stored in the variable

The Python language itself does not support regular expressions, and dependent re modules (python1.5 versions are introduced) support regular expressions. There are two methods of searching and matching to complete the matching pattern. Re modules commonly used functions and methods are Complie, match, search, find and FindAll and so on. The pattern must be compiled into a Regex object before the re is used for matching.

Table 4. Python Common Matching pattern

Grammar Description Sample
. matches any character except \ n of a newline character B.C Matching BAC,BDC
* Matches the previous character 0 or more times B*c match C, or BBBC
+ Matches the previous character 1 or more times B+c match BC or BBBC
Matches a previous character 0 or 1 times B?c match C or BC
{m} Match a previous character m times B{2}c match BBC
{M,n} Matches a previous character M to n times B{2,5}c match BBC or BBBBC
[ABC] Match any character within [] [BC] Match B or C
\d Matching number [0-9] B\DC Matching b1c etc.
\d Match non-numeric, equivalent to [^\d] B\DC matched BAc
\s Match White-space characters B\SC Match b C
\s Matching Non-white-space characters [\^s] B\sc matched BAC
\w Match [a-za-z0-9_] B\WC matched BAc etc
\w equivalent to [^\w] B\WC Match b C
\ Escape character, b\\c Matching b\c
^ Match string start ^BC match the first BC of the sentence
$ Match end of string bc$ matches a string ending with a BC
\a Matches only the beginning of a string \ABC a BC that matches the beginning of a string
\z Matches only the end of a string Bc\z a BC that matches the end of a string
| Match any one of the left and right expressions B|c Match B or C

Perl and the threads in Python
A thread is a single execution process that is the smallest unit of control that can be dispatched by the CPU. The lifecycle of a thread in Perl includes the three phases of creating, running, and exiting. A thread runs like the execution of a normal function, but the execution of a new thread is parallel to the execution of the current thread.

There are two ways to create threads in Perl:

Listing 2. Create () method using the Threads package

Copy Code code as follows:

Use threads;
Sub Say_hello
printf ("Hello thread! @_.\n ");
Return (rand (10));
My $t 1 = threads->create (\&say_hello, "param1", "param2");

Listing 3. To create a thread using the async{} block

Copy Code code as follows:

Use threads;
My $t 4 = async{
printf ("Hello thread!\n");

There are two ways to control the execution of a thread, one is join () and one is detach (). A join () is a thread that waits for the execution return of a child thread in the main thread, and then continues execution of subsequent code, which is separate from the execution of the main thread before the join () method is invoked. The detach () tells the interpreter that the main thread does not care about the execution result of the child, so the child thread exits automatically after completing the task, releasing its own resources instead of being bothered by the main thread.

Perl defaults to any data structure that is not shared, and any newly created thread has a private copy of the current data. If you want to share data, you must use Threads::shard to display the declaration.

Such as:

Copy Code code as follows:

My $var: shared = 0; # Use:share tag to define
My @array: Shared = (); # Use:share tag to define
My%hash = ();
Share (%hash); # Use Share () funtion to define

The Perl thread also supports the lock mechanism, which enables you to use the lock method to implement a locking mechanism for sharing data between threads. The Thread::semaphore package in Perl provides semaphore support for threads, and thread::queue packages provide thread-safe queue support for threads. More readers can access the relevant documents themselves.

Python provides several modules for multithreaded programming, including thread, threading, and Queue. The thread and threading modules allow programmers to create and manage threads. The thread module provides basic thread and lock support, while threading provides a higher level of functionality for more powerful threading management. The queue module allows users to create a queue data structure that can be used to share data between multiple threads.

There are also two ways to create Python threads, one using the Start_new_thread () function of the thread module to generate new threads.

Copy Code code as follows:

Import time
Import Thread
def timer (no, interval):
CNT = 0
While cnt<10:
print ' Thread: (%d) time:%s/n '% (No, time.ctime ())
Time.sleep (interval)
Thread.exit_thread ()
def test (): #Use thread.start_new_thread () to create 2 new threads
Thread.start_new_thread (Timer, (1,1))
Thread.start_new_thread (Timer, (2,2))

If __name__== ' __main__ ':
Test ()

The other is to create a threading. A subclass of thread to wrap a thread object.

Copy Code code as follows:

Class Timer (threading. Thread): # derived from the class threading. Thread
def __init__ (self, num, interval):
Threading. Thread.__init__ (self)
Self.thread_num = num
Self.interval = Interval
Self.thread_stop = False
def run (self): #Overwrite run () method, put what your want the thread do
While not self.thread_stop:
print ' Thread Object (%d), time:%s/n '% (Self.thread_num, time.ctime ())
Time.sleep (Self.interval)
def stop (self):
Self.thread_stop = True

The Python thread also provides synchronization mechanisms that can take advantage of the Thrading module's threading. Rlock and Hreading. Condition can implement lock mechanism and condition variable respectively.

where the Acquire () and release () methods acquire and free locks respectively.

Copy Code code as follows:

def run (self):
Global X
Lock.acquire ()
For I in range (3):
x = x + 1
Time.sleep (2)
Print X
Lock.release ()

For more information about threads, readers can consult related documents.

This paper compares the origins of Perl and Python, basic data types, control structures, functions, packages and modules, object-oriented, regular expressions, and threads, so that developers who need to master both scripting languages must be consulted for better understanding and application.

Reference Study

      > Looking for Linux developers in DeveloperWorks Linux area (including Linux Beginner's primer) For more resources, check out our most popular articles and tutorials.

    • reference Tutorial Perl official documentation to focus on more Perl dynamics. The

    • reference Tutorial python to view the official Python documentation.
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.