(~) 53%
perl time.plThe time is now Thu Sep 16 17:30:02 1999
Mechanics of Writing Perl Scripts
Some hints to help you get going.
Creating the Script
A Perl script is just a text file. Use any text (programmer's) editor.
By convention, Perl script files end with the extension .pl.
The Emacs text editor has a Perl mode that will auto-format your Perl scripts and highlight keywords. Perl mode will be activated automatically if you end the script name with .pl. Otherwise, you can force Emacs to enter Perl mode by placing this line somewhere near the top of the file:
# -*- mode: perl -*-
The next time you open the file, Emacs will enter Perl mode.
Running the Script
Option 1Run the
perl program from the command line, giving it the name of the script file to run.
(~) 50% perl time.pl The time is now Thu Sep 16 18:09:28 1999
Option 2Put the magic comment
#!/usr/bin/perl at the top of the script.
#!/usr/bin/perl# file: time.pl$time = localtime;print "The time is now $time\n"; |
Make the script executable with
chmod +x time.pl:
(~) 51% chmod +x time.pl
Run the script as if it were a command:
(~) 52% time.pl The time is now Thu Sep 16 18:12:13 1999
Common Errors
Every script goes through a few iterations before you get it right. Here are some common errors:
Syntax Errors
Code:
#!/usr/bin/perl # file: time.pl time = localtime; print "The time is now $time\n"; |
Output:
(~) 53% time.plCan't modify time in scalar assignment at time.pl line 3, near "localtime;"Execution of time.pl aborted due to compilation errors.
Runtime Errors
Code:
#!/usr/bin/perl # file: math.pl $six_of_one = 6; $half_dozen = 12/2; $result = $six_of_one/($half_dozen - $six_of_one); print "The result is $result\n"; |
Output:
(~) 54% math.plIllegal division by zero at math.pl line 6.
Forgetting to Make the Script Executable
(~) 55% test.pltest.pl: Permission denied.
Getting the Path to Perl Wrong on the #! line
Code:
#!/usr/local/bin/pearl # file: time.pl $time = localtime; print "The time is now $time\n"; |
(~) 55% time.pltime.pl: Command not found.
Useful Perl Command-Line Options
You can call Perl with a few command-line options to help catch errors:
-cPerform a syntax check, but don't run.
-wTurn on verbose warnings.
-dTurn on the Perl debugger.
Usually you will invoke these from the command-line, as in perl -cw time.pl (syntax check time.pl with verbose warnings). You can also put them in the top line: #!/usr/bin/perl -w.
CHECK OUT Perl Basics 2!