The pros and cons of Python and Perl

Source: Internet
Author: User
Tags define function scalar perl script python script



One: Python vs. Perl



(1) The initial purpose of designing a language determines what features the language will be built in:



Perl was originally created for the formatting of text, so the built-in regular, Python built a complex type, guess Guido initially must have created Python for numerical computation. So perl is good at word processing and Python is good at numerical processing.



(2) Application areas and requirements are different:



Perl was designed to facilitate the writing of complex and efficient system scripts , which is also the most widely used scripting language. It is equivalent to the Swiss Army knife in programming, the ability to handle characters and text files is very strong, the task previously required shell+sed+awk+c to complete, just the Perl script can be completed. And the field of application has been broadened to support object-oriented programming.



Python's object-oriented, dynamic common language, suitable for scripting and rapid development , is most notable for its powerful functionality as a bridging language between compiled languages such as C and scripting languages such as Perl. Extensibility and object-oriented features make it a large-scale application development tool.



(3) About strong types



The type of data in the Perl language, depending on the context in which the data is located.



In the Python language, the data type is determined by the data itself. Python is therefore generally considered a strongly typed language, while Perl is not.



(4) about built-in base types



The basic type of Perl is called scalar, which distinguishes it from the following array and hash. Scalar can be a number, or it can be a string. Basically, scalar is either, in other words, scalar is both a number and a string. Whether a scalar is a string or a number depends entirely on the context in which it is used, and if it is a function that handles a string, it is a string, and if it is a function that handles numbers, it is a number. Perl will make every effort to accomplish the transformation between them, no matter how absurd you seem. In Perl, all the scalar starts with $ and all the scalar that begins with $.



The underlying type of Python, again, not a number, is a string. However, it cannot be both a number and a string. Python will determine whether a variable is a number, or a string, to choose how to interpret the function, and if it cannot find an appropriate explanation, then Python throws an exception. In general, this strategy pleases a part of the programmer while making another part of the person feel uncomfortable.



(5) About composite types



There are two composite types of Perl: array and hash. Python has three kinds of composite types: tuple, list, Dict. The tuple+list in Python corresponds exactly to the array in Perl, so there's no such thing as a richer type.



(6) about the list as a whole



In Perl, the name at the beginning of the @ represents the entire array, which is said to be the word header of the array. However, in accordance with Perl principles, @foo Such an array can also be used in a scalar environment, Perl will try to convert @foo into a scalar, in general, this scalar is the length of @foo. In Python, you can get the entire list (or tuple) by using the variable name directly.



Two: A preliminary study of Python



(1) Let's step into the world of Python



(2) Introduction to Skills



1---The Python script, which is run under CMD






2---Input and output on the Python console






3– evil ":" instead of {} too good, the organization of the statement depends on the contraction and not the begin/end block, so the indentation must be controlled;



4--does not require a variable or parameter declaration.



5--python can write very compact and highly readable programs. Programs written in Python are usually much shorter than the same C or C + + programs



6--the main prompt to execute, the main prompt is typically identified as three greater than (">>>"), and the continuation is referred to as a subordinate prompt, Identified by three dots ("... " ). Two consecutive carriage returns to end the dependent prompt, which becomes the usual identifier >>>



The 7--python script can be executed directly as a shell script, as long as a line command is written at the beginning of the script file specifying the file and schema:



#!/usr/bin/env python



(the user path is notified to the interpreter) "#!" Must be the first two characters of the file, on some platforms, the first line must end with a Unix-style line Terminator ("\ n"), not with the Terminator of the Mac ("\ r") or Windows ("\ r \ n"). Note that "#" is the starting character of the line comment in Python .



8--



Python's source files can be encoded using a character set other than ASCII. The best thing to do is to #! The line is followed by a special comment line to define the character set.



#-*-Coding:iso-8859-1-*-


According to this statement,Pythonconverts the characters in the file as far as possible from the specified encoding toUnicode, in this case, this character set isISO-8859-1. In thea list of available encodings can be found in the Python Library Reference manual (according to my experiment, Chinese seems to only useCP-936orUTF-8, notDirect SupportGB,GBK,GB-18030orISO-10646--The translator's note).


9-- Pass The statement does nothing. If Exp:elif exp:else:



It is used for situations where there is a grammatical need to have a statement, but nothing is done on the program, for example:  



>>> while True:



... Pass # busy-wait for Keyboardinterrupt



...



If n > 0:



sum = 1;



elif n = = 0:



sum = 0



Else



sum =-1;



10--Define function
The keyword def introduces a function definition. Must be followed by a function name and parentheses that include formal parameters. The function body statement starts at the next line and must be indented. The first line of the function body can be a string value, which is the document string for the function, or it can be called a docstring.
Some document string tools can process or print documents online, or browse code that lets users interact; it is a good practice to include a document string in your code, and you should develop a habit.



11-- by lambda keyword, you can create very small anonymous functions


through lambda keyword, you can create very small anonymous functions. Here is a function that returns the and of its two parameters: "LambdaA, b:a+b". Lambdathe form can be used for any function object that is required. They can only have a single expression for syntax restrictions. Semantically, they are only a grammatical technique in the definition of common functions.

- - delStatement


there is a way to remove elements from a linked list for a specified index: del statement. This method can also delete slices from the list (we previously assigned an empty list to the slice). For example:



>>> a = [-1, 1, 66.6, 333, 333, 1234.5]



>>> del A[0]



>>> A



[1, 66.6, 333, 333, 1234.5]



>>> del A[2:4]



>>> A



[1, 66.6, 1234.5]



Del can also be used to delete the entire variable:



>>>del A



Three: the actual combat chapter





# coding = utf-8
#! / usr / bin / python

import xml.sax
# Inheritance syntax class Derived class name (base class name): // ... The base class name is written in parentheses. The base class is specified in the tuple when the class is defined.
class MovieHandler (xml.sax.ContentHandler):
   def __init __ (self):
      self.CurrentData = ""
      self.type = ""
      self.format = ""
      self.year = ""
      self.rating = ""
      self.stars = ""
      self.description = ""

   # Element start event processing
   def startElement (self, tag, attributes):
      self.CurrentData = tag
      if tag == "movie":
         print "***** Movie *****"
         title = attributes ["title"]
         print "Title:", title

   # Element end event processing
   def endElement (self, tag):
      if self.CurrentData == "type":
         print "Type:", self.type
      elif self.CurrentData == "format":
         print "Format:", self.format
      elif self.CurrentData == "year":
         print "Year:", self.year
      elif self.CurrentData == "rating":
         print "Rating:", self.rating
      elif self.CurrentData == "stars":
         print "Stars:", self.stars
      elif self.CurrentData == "description":
         print "Description:", self.description
      self.CurrentData = ""

   # Content event processing
   def characters (self, content):
      if self.CurrentData == "type":
         self.type = content
      elif self.CurrentData == "format":
         self.format = content
      elif self.CurrentData == "year":
         self.year = content
      elif self.CurrentData == "rating":
         self.rating = content
      elif self.CurrentData == "stars":
         self.stars = content
      elif self.CurrentData == "description":
         self.description = content
  
if (__name__ == "__main__"):
   
   # Create an XMLReader
   parser = xml.sax.make_parser ()
   # turn off namepsaces
   parser.setFeature (xml.sax.handler.feature_namespaces, 0)

   # Override ContextHandler
   Handler = MovieHandler ()
   parser.setContentHandler (Handler)
   
   parser.parse ("movies.xml")
   
   
def foo (bar = []): # bar is optional, if not specified, the default value is []
bar.append ("MKY"); # But this line is problematic, just walk around ...
return bar;
print foo ()
print foo ()

odd = lambda x: bool (x% 2)
nums = [n for n in range (10)]
nums [:] = [n for n in nums if not odd (n)] # Ah, how beautiful
print nums 
This example is primarily for sax_xml reading, as well as defining parameter defaults for functions and application of Lambda anonymous functions






The pros and cons of Python and Perl


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: info-contact@alibabacloud.com 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.