|May the source be with you, but remember the KISS principle ;-)|
|Contents||Bulletin||Scripting in shell and Perl||Network troubleshooting||History||Humor|
Contents : Foreword : Ch01 : Ch02 : Ch03 : Ch04 : Ch05 : Ch06 : Ch07 : Ch08 :
Prev | Up | Contents | Down | Next
The classic way to start learning a new language is to write a so called "Hello world" program. This program can tell a lot about the language.
#!/usr/local/bin/perl -w # Hello.pl -- Program to print the classic phrase Hello world print "Hello world\n"; # Print a message
As one can, see the program Hello.pl consists of three lines. The first two are comments starting with #. The last is the only executable line, and it contains a print statement starting with the keyword print
Actually the very first line is not a true comment -- it's a directive used in Unix (this can make sense in Windows if you are using Unix shell port to this OS, for example bash has a pretty good and free Windows port in Cygwin utilities). It specifies the interpreter to be used for a particular text file.
Comments in Perl are self-delimiting Fortran-style comments used also in all Unix shells. They start with the # symbol, and always end at the end of the line.
The print function writes to the standard output stream which by default is a console. In this case it writes a string Hello world; please note that as in C "\n" is escape sequence for a newline.
Perl belongs to so-called PL/1-style languages (C also belongs to this group): each Perl statement should end with a semicolon. It is wise to check if all semicolons present before running the script through the Perl interpreter as the diagnostic messages for this type of error are often misleading.
Text literals should be included in double quotes and \n should inserted whenever you need a newline
Now you probably understand that the actual program is a one-liner:
print "Hello world\n"; # Print a message
Copy this program into the text editor, and save it as a file named hello.pl. Then from the command line please type
That will execute the program and you should see the message on your console. Actually Perl first compiles the program into intermediate code and only then executes that compiled version. Now let's change our invocation as the following:
perl -wc hello.pl
The -w is a warning flag and for new scripts one should always run the Perl interpreter with this flag. The flag -c will block running the script and is a recommended flag for use with -w. You can use -wc as a shorthand. In Unix you can also make the file executable by using the command: chmod u+x hello.pl and then run the program using ./hello.pl. In this case the location of Perl interpreter should be specified in the first line which should look like
If there are lexical or syntax errors in your script you may get error messages.
Now let's introduce some errors and see what will happen. The first thing to try is to use Print or PRINT instead of print. Perl is case sensitive and you will get errors like:
String found where operator expected at t line 1, near "Print "Hello world\n"" (Do you need to predeclare Print?)
syntax error at hello.pl line 1, near "Print "Hello world\n""
Execution of hello.pl aborted due to compilation errors.
You will instantly see that error messages are definitely intimidating for beginning users. It seems like the error messages that you get have virtually no relationship whatsoever to what you did wrong. I'm wondering, is that because of the weak design of Perl syntax parser or an inherent limitation of the obscure syntax of the language, but I tend to suspect that it's the former.
I would like to stress the importance of using -wc combination of flag as a first stage of testing of any new script. Those flags instruct the Perl interpreter to display additional warnings and other (hopefully) helpful messages without executing the program.
Let's make a program slightly more complex by adding a second print statement:
# Hello2.pl -- Program to print two phrases print "Hello world\n"; # Print message 1 print "Hello Perl\n"; # Print message 2
Now try to introduce another typical for Perl error into the program. First remove opening double quote in the first print statement and rerun the program. You will see an error message or several error messages. You can reasonably expect that one of them will be more or less close to the real source of error. As you will see later this is usually not the case ;-). That means that sometimes finding an error means commenting out "suspect" statement(s) and rerunning script again and again...
Now let's try to remove the final semicolon in the first print statement, and see what will happen. You will see a message similar to:
Execution of hello2.pl aborted due to compilation errors.
Please note that the message points to the line after the error, not to the line with an error. Also the message does not inform you what's wrong -- it just states that there is a syntax error.
That's means that manual check against typical errors listed in summary of this Chapter is an extremely useful stage that can save a lot of time and frustration.
It makes sense to manually check for the presence of semicolons at the end of statements, matching quotes and other typical errors each statement of your script before running it through Perl interpreter
Run time errors are more complex beast then syntax errors. See debugging for more information. One good thing about Perl is that contains an excellent command line debugger that is supplied as a part of interpreter.
To run the program using a built-in debugger please use the command perl -d filename. In case of hello2.pl it will be (please do not forget to restore the program to its correct state before that) :
perl -d hello2.pl
After a short pause you will see a prompt
main::(hello2.pl:3): print "Hello world\n"; # Print a message
Then print the debugger command n (next) to trace the program step by step. Our program contains two statements, so the second step actually will end the execution of the program:
DB<2> n Hello world Debugged program terminated. Use q to quit or R to restart, use O inhibit_exit to avoid stopping after program termination, h q, h R or h O to get additional info. DB<2>
Generally the n command executes one line of your program and displays the next line to be executed. That is a very important command for understanding what the program is actually doing. At any time you can print values of variables using the p command. That gives you a possibility of finding bugs in case you program produces results different than expected.
Rerun the debugger and list the program using l command. Than set breakpoint on the line 2 using the b 2 command. After that run the program to the breakpoint using c command.
Actually the quality of the debugger to a large extent determines the quality of the language and in this respect Windows implementation of Perl is stronger, as it has (commercial) debugger from ActiveState. ActiveState port of Perl interpreter for Win32 environment is also the best -- I do not recommend using other Windows ports.
One can also use print statements as a debugging tool, but this is not very flexible. One of advantages of Perl is that you can make it more flexible yourself by using special comments and generating print statements with a special Perl script, but it's too early to discuss this possibility.
Before you think about debugging, you need to eliminate as many errors as possible, using diagnostics of the Perl interpreter. Again, usage of the -wc combination of flags as a pseudo compilation stage and first eliminate all errors on this stage.
One should always first test Perl programs with -wc switches: perl -wc progname
To debug a Perl script, one should use -d switch.
There are five extremely useful commands in the Perl debugger
n -- next
p -- print
c <linenumber> -- run to the breakpoint -- this is very important directive. Please learn how to use it
b <linenumber> -- set breakpoint -- this is very important directive. Please learn how to use it
d - delete breakpoint
l -- list your script
h -- produces list of debugger commands. Useful if you forgot mnemonic
To debug a Perl script, one should use -d switch. The most useful debugger command is c -- run to breakpoint. The h command produce listing of debugging commands.
I would like to reiterate that Perl is a difficult language to master. Exacerbating all problems with the language are the diagnostics the interpreter generate, which are sometimes cruelly misleading and often uninformative. Complaints that something is wrong on line X can often mean that the error is several lines above or below. In no way one should rely on lines numbers that Perl interpreter will include in the error message. Consider it as a very fuzzy pointer and search the vicinity.
Now let's reiterate the most typical beginners errors in Perl scripts:
The absence of the semicolon at the end of statement.
A missing quote.
Wrong case in Perl keywords or identifiers (Perl is case sensitive).
Trying to debug a Perl script without first checking it, using -wc flag.
Not knowing how to use debugger (especially breakpoint feature) to test you program.
In view of this problems (several additional problems like leaving out '$' or '@' at the beginning of variables) we should not jump to debugging before checking for typical syntax and semantic errors. All programming languages have some annoying conventions and all of them provide you with opportunities to write obscure bugs, so it's not worth discarding Perl just because of these issues. For more information about Perl traps see Perl traps for the unwary
Perl design decisions are based on Unix user familiarity rather than usability. Perl simply borrowed the notation from earlier languages, borrowing some of typical errors as well. This decision has both strong and weak points. the latter are connected with the fact that the benefits of the familiarity approach only help users who know the older languages. For the majority of the scripting market this isn't necessarily true.
But weak points can be minimized by using a good programming editor which can help to write code and provide syntax highlighting for Perl. Using a good editor can make the language much more pleasant to use. Komodo is one such editor and it is available from ActiveState, but while it is IDE with good access to debugger it is rather expensive ($300). Eclipse is another, free alternative but it is very heavyweight.
Using a good editor can make the language much more pleasant to use.
For small scripts lightweight editors are adequate. For the selection of lightweight editors in win32 environment see Win32 editors page.
Softpanorama hot topic of the month
Prev | Up | Contents | Down | Next
FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available in our efforts to advance understanding of environmental, political, human rights, economic, democracy, scientific, and social justice issues, etc. We believe this constitutes a 'fair use' of any such copyrighted material as provided for in section 107 of the US Copyright Law. In accordance with Title 17 U.S.C. Section 107, the material on this site is distributed without profit exclusivly for research and educational purposes. If you wish to use copyrighted material from this site for purposes of your own that go beyond 'fair use', you must obtain permission from the copyright owner.
ABUSE: IPs or network segments from which we detect a stream of probes might be blocked for no less then 90 days. Multiple types of probes increase this period.
Groupthink : Two Party System as Polyarchy : Corruption of Regulators : Bureaucracies : Understanding Micromanagers and Control Freaks : Toxic Managers : Harvard Mafia : Diplomatic Communication : Surviving a Bad Performance Review : Insufficient Retirement Funds as Immanent Problem of Neoliberal Regime : PseudoScience : Who Rules America : Neoliberalism : The Iron Law of Oligarchy : Libertarian Philosophy
War and Peace : Skeptical Finance : John Kenneth Galbraith :Talleyrand : Oscar Wilde : Otto Von Bismarck : Keynes : George Carlin : Skeptics : Propaganda : SE quotes : Language Design and Programming Quotes : Random IT-related quotes : Somerset Maugham : Marcus Aurelius : Kurt Vonnegut : Eric Hoffer : Winston Churchill : Napoleon Bonaparte : Ambrose Bierce : Bernard Shaw : Mark Twain Quotes
Vol 25, No.12 (December, 2013) Rational Fools vs. Efficient Crooks The efficient markets hypothesis : Political Skeptic Bulletin, 2013 : Unemployment Bulletin, 2010 : Vol 23, No.10 (October, 2011) An observation about corporate security departments : Slightly Skeptical Euromaydan Chronicles, June 2014 : Greenspan legacy bulletin, 2008 : Vol 25, No.10 (October, 2013) Cryptolocker Trojan (Win32/Crilock.A) : Vol 25, No.08 (August, 2013) Cloud providers as intelligence collection hubs : Financial Humor Bulletin, 2010 : Inequality Bulletin, 2009 : Financial Humor Bulletin, 2008 : Copyleft Problems Bulletin, 2004 : Financial Humor Bulletin, 2011 : Energy Bulletin, 2010 : Malware Protection Bulletin, 2010 : Vol 26, No.1 (January, 2013) Object-Oriented Cult : Political Skeptic Bulletin, 2011 : Vol 23, No.11 (November, 2011) Softpanorama classification of sysadmin horror stories : Vol 25, No.05 (May, 2013) Corporate bullshit as a communication method : Vol 25, No.06 (June, 2013) A Note on the Relationship of Brooks Law and Conway Law
Fifty glorious years (1950-2000): the triumph of the US computer engineering : Donald Knuth : TAoCP and its Influence of Computer Science : Richard Stallman : Linus Torvalds : Larry Wall : John K. Ousterhout : CTSS : Multix OS Unix History : Unix shell history : VI editor : History of pipes concept : Solaris : MS DOS : Programming Languages History : PL/1 : Simula 67 : C : History of GCC development : Scripting Languages : Perl history : OS History : Mail : DNS : SSH : CPU Instruction Sets : SPARC systems 1987-2006 : Norton Commander : Norton Utilities : Norton Ghost : Frontpage history : Malware Defense History : GNU Screen : OSS early history
The Peter Principle : Parkinson Law : 1984 : The Mythical Man-Month : How to Solve It by George Polya : The Art of Computer Programming : The Elements of Programming Style : The Unix Haterís Handbook : The Jargon file : The True Believer : Programming Pearls : The Good Soldier Svejk : The Power Elite
Most popular humor pages:
Manifest of the Softpanorama IT Slacker Society : Ten Commandments of the IT Slackers Society : Computer Humor Collection : BSD Logo Story : The Cuckoo's Egg : IT Slang : C++ Humor : ARE YOU A BBS ADDICT? : The Perl Purity Test : Object oriented programmers of all nations : Financial Humor : Financial Humor Bulletin, 2008 : Financial Humor Bulletin, 2010 : The Most Comprehensive Collection of Editor-related Humor : Programming Language Humor : Goldman Sachs related humor : Greenspan humor : C Humor : Scripting Humor : Real Programmers Humor : Web Humor : GPL-related Humor : OFM Humor : Politically Incorrect Humor : IDS Humor : "Linux Sucks" Humor : Russian Musical Humor : Best Russian Programmer Humor : Microsoft plans to buy Catholic Church : Richard Stallman Related Humor : Admin Humor : Perl-related Humor : Linus Torvalds Related humor : PseudoScience Related Humor : Networking Humor : Shell Humor : Financial Humor Bulletin, 2011 : Financial Humor Bulletin, 2012 : Financial Humor Bulletin, 2013 : Java Humor : Software Engineering Humor : Sun Solaris Related Humor : Education Humor : IBM Humor : Assembler-related Humor : VIM Humor : Computer Viruses Humor : Bright tomorrow is rescheduled to a day after tomorrow : Classic Computer Humor
The Last but not Least
Copyright © 1996-2016 by Dr. Nikolai Bezroukov. www.softpanorama.org was created as a service to the UN Sustainable Development Networking Programme (SDNP) in the author free time. This document is an industrial compilation designed and created exclusively for educational use and is distributed under the Softpanorama Content License.
Original materials copyright belong to respective owners. Quotes are made for educational purposes only in compliance with the fair use doctrine.
FAIR USE NOTICE This site contains copyrighted material the use of which has not always been specifically authorized by the copyright owner. We are making such material available to advance understanding of computer science, IT technology, economic, scientific, and social issues. We believe this constitutes a 'fair use' of any such copyrighted material as provided by section 107 of the US Copyright Law according to which such material can be distributed without profit exclusively for research and educational purposes.
This is a Spartan WHYFF (We Help You For Free) site written by people for whom English is not a native language. Grammar and spelling errors should be expected. The site contain some broken links as it develops like a living tree...
|You can use PayPal to make a contribution, supporting development of this site and speed up access. In case softpanorama.org is down you can use the at softpanorama.info|
The statements, views and opinions presented on this web page are those of the author (or referenced source) and are not endorsed by, nor do they necessarily reflect, the opinions of the author present and former employers, SDNP or any other organization the author may be associated with. We do not warrant the correctness of the information provided or its fitness for any purpose.
Last modified: December 22, 2017