Learning Perl: 1.4. How Do I Make a Perl Program?

Previous Page

Next Page

 

1.4. How Do I Make a Perl Program?

It's about time you asked (even if you didn't). Perl programs are text files; you can create and edit them with your favorite text editor. (You don't need any special development environment,though some commercial ones are available from various vendors. We've never used any of these enough to recommend them.)

You should generally use a programmers' text editor,rather than an ordinary editor. What's the difference? Well,a programmers' text editor will let you do things that programmers need,like indent or unindent a block of code or to find the matching closing curly brace for a given opening curly brace. On Unix systems,the two most popular programmers' editors are emacs and vi (and their variants and clones). BBEdit and Alpha are good editors for Mac OS X,and a lot of people have said nice things about UltraEdit and Programmer's Favorite Editor (PFE) on Windows. The perlfaq2 manpage lists several other editors,too. Ask your local expert about text editors on your system.

For the simple programs you'll write for the exercises in this book,none of which should be more than about twenty or thirty lines of code,any text editor will be fine.

A few beginners try to use a word processor instead of a text editor. We recommend against this because it's inconvenient at best and impossible at worst. But we won't try to stop you. Be sure to tell the word processor to save your file as "text only"; the word processor's own format will almost certainly be unusable. Most word processors will probably tell you that your Perl program is spelled incorrectly and should use fewer semicolons.

In some cases,you may need to compose the program on one machine and transfer it to another to run it. If you do this,be sure that the transfer uses "text" or "ASCII" mode and not "binary" mode. This step is needed because of the different text formats on different machines. Without that,you may get inconsistent results. Some versions of Perl abort when they detect a mismatch in the line endings.

1.4.1. A Simple Program

According to the oldest rule in the book,any book about a computer language that has Unix-like roots has to start with showing the "Hello,world" program. So,here it is in Perl:

    #!/usr/bin/perl
    print "Hello,world!/n";

Let's imagine that you've typed that into your text editor. (Don't worry yet about what the parts mean and how it works. We'll see about those in a moment.) You can generally save that program under any name you wish. Perl doesn't require any special kind of filename or extension,and it's better to use no extension at all.[*] But some systems may require an extension like .plx (meaning PerL eXecutable); see your system's release notes for more information.

[*] Why is it better to have no extension? Imagine that you've written a program to calculate bowling scores and you've told all of your friends that it's called bowling.plx. One day you decide to rewrite it in C. Do you still call it by the same name,implying that it's still written in Perl? Or do you tell everyone that it has a new name? (And don't call it bowling.c,please!) The answer is that it's none of their business what language it's written in if they're merely using it. So,it should have simply been called bowling in the first place.

You may need to do something so your system knows it's an executable program (that is,a command). What you'll do depends upon your system; maybe you won't have to do anything more than to save the program in a certain place. (Your current directory will generally be fine.) On Unix systems,you mark a program as being executable by using the chmod command,perhaps like this:

    $ chmod a+x my_program

The dollar sign (and space) at the start of the line represents the shell prompt,which will probably look different on your system. If you're used to using chmod with a number like 755 instead of a symbolic parameter like a+x,that's fine,too. Either way,it tells the system that this file is now a program.

Now you're ready to run it:

    $ ./my_program

The dot and slash at the start of this command mean to find the program in the current working directory. That's not needed in all cases,but you should use it at the start of each command invocation until you fully understand what it's doing.[*] If everything worked,it's a miracle. More often,you'll find that your program has a bug. Edit and try again,but you don't need to use chmod each time since that should "stick" to the file. (Of course,if the bug is that you didn't use chmod correctly,you'll probably get a "permission denied" message from your shell.)

[*] In short,it's preventing your shell from running another program (or shell built-in) of the same name. A common mistake among beginners is to name their first program test. Many systems have a program (or shell built-in) with that name; that's what the beginners run instead of their program.

1.4.2. What's Inside That Program?

Like other "free-form" languages,Perl generally lets you use insignificant whitespace (like spaces,tabs,and newlines) at will to make your program easier to read. Most Perl programs use a fairly standard format though,much like most of what we show here. We strongly encourage you to indent your programs properly since that makes your program easier to read; a good text editor will do most of the work for you. Good comments make a program easier to read. In Perl,comments run from a pound sign (#) to the end of the line. (There are no "block comments" in Perl.)[

] We don't use many comments in the programs in this book because the surrounding text explains their workings,but you should use comments as needed in your own programs.

[

] But there are a number of ways to fake them. See the FAQ (accessible with perldoc perlfaq on most installations).

So another way (a strange way,it must be said) to write that same "Hello,world" program might be like this:

    #!/usr/bin/perl
        print    # This is a comment
    "Hello,world!/n"
      ;    # Don't write your Perl code like this!

That first line is a special comment. On Unix systems,[*] if the first two characters on the first line of a text file are "#!",then what follows is the name of the program that executes the rest of the file. In this case,the program is stored in the file /usr/bin/perl.

[*] Most modern ones,anyway. The "shebang" mechanism pronounced "sheh-bang," as in "the whole shebang" was introduced somewhere in the mid-1980s,and that's pretty ancient,even on the extensively long Unix timeline.

This #! line is the least portable part of a Perl program because you'll need to find out what goes there for each machine. Fortunately,it's almost always /usr/bin/perl or /usr/local/bin/perl. If that's not it,you'll have to find where your system is hiding perl and use that path. On Unix systems,you might use a shebang line that finds perl for you:

    #!/usr/bin/env perl

If perl isn't in any of the directories in your search path,you might have to ask your local system administrator or somebody using the same system as you.

On non-Unix systems,it's traditional (and even useful) to make the first line say #!perl. If nothing else,it tells your maintenance programmer as soon as he or she gets ready to fix it that it's a Perl program.

If that #! line is wrong,you'll generally get an error from your shell. This may be something unexpected,like "file not found." It's not your program that's not found though; it's /usr/bin/perl that wasn't where it should have been. We'd make the message clearer,but it's not coming from Perl; it's the shell that's complaining. (By the way,you should be careful to spell it usr and not user because the folks who invented Unix were lazy typists,so they omitted a lot of letters.)

Another problem you could have is if your system doesn't support the #! line at all. In that case,your shell (or whatever your system uses) will probably run your program by itself,with results that may disappoint or astonish you. If you can't figure out what some strange error message is telling you,search for it in the perldiag manpage.

The "main" program consists of all of the ordinary Perl statements (not including anything in subroutines,which you'll see later). There's no "main" routine,as there is in languages like C or Java. In fact,many programs don't have routines (in the form of subroutines).

There's no required variable declaration section as there is in some other languages. If you've always had to declare your variables,you may be startled or unsettled by this at first. But it allows us to write quick-and-dirty Perl programs. If your program is only two lines long,you don't want to have to use one of those lines just to declare your variables. If you want to declare your variables,that's a good thing; you'll see how to do that in Chapter 4.

Most statements are an expression followed by a semicolon. Here's the one you've seen a few times so far:

    print "Hello,world!/n";

As you may have guessed by now,this line prints the message Hello,world!. At the end of that message is the shortcut /n,which is probably familiar to you if you've used another language like C,C++,or Java; it means a newline character. When that's printed after the message,the print position drops down to the start of the next line,allowing the following shell prompt to appear on a line of its own rather than being attached to the message. Every line of output should end with a newline character. We'll see more about the newline shortcut and other so-called backslash escapes in the next chapter.

1.4.3. How Do I Compile Perl?

Just run your Perl program. The perl interpreter compiles and then runs your program in one user step.

    $ perl my_program

When you run your program,Perl's internal compiler first runs through your entire source,turning it into internal bytecode,which is an internal data structure representing the program. Perl's bytecode engine takes over and runs the bytecode. If there's a syntax error on line 200,you'll get that error message before you start running line two.[*] If you have a loop that runs 5,000 times,it's compiled once; the loop can then run at top speed. And there's no runtime penalty for using as many comments and as much whitespace as you need to make your program easy to understand. If you use calculations involving only constants the result will be a constant computed once as the program is beginning,not each time through a loop.

[*] Unless line two happens to be a compile-time operation,like a BEGIN block or a use invocation.

To be sure,this compilation does take time. It's inefficient to have a voluminous Perl program that does one small quick task (out of many potential tasks,say) and then exits because the runtime for the program will be dwarfed by the compile time. But the compiler is fast; normally the compilation will be a tiny percentage of the runtime.

An exception might be if you were writing a program run as a CGI script,where it may be called hundreds or thousands of times every minute. (This is a high usage rate. If it were called a few hundreds or thousands of times per day,like most programs on the Web,we probably wouldn't worry too much about it.) Many of these programs have short runtimes,so the issue of recompilation may become significant. If this is an issue for you,you'll want to find a way to keep your program in memory between invocations. The mod_perl extension to the Apache web server http://perl.apache.org or Perl modules like CGI::Fast can help you.

What if you could save the compiled bytecode to avoid the overhead of compilation? Or,even better,what if you could turn the bytecode into another language,like C,and then compile that? Well,both of these things are possible in some cases,but they probably won't make most programs any easier to use,maintain,debug,or install,and they may make your program slower. Perl 6 should do a lot better in this regard,although it is too soon to tell (as we write this).

Previous Page

Next Page

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


1. 如何去重 #!/usr/bin/perl use strict; my %hash; while(<>){ chomp; print "$_n" unless
最近写了一个perl脚本,实现的功能是将表格中其中两列的数据进行拼凑,然后将拼凑后的数据用“|”连接在一起。表格内容如下: 员工号码员工姓名职位入职日期1001张三销售1980/12/17 0:00:
表的数据字典格式如下:如果手动写MySQL建表语句,确认麻烦,还不能保证书写一定正确。写了个Perl脚本,可快速构造MySQL脚本语句。脚本如下:#!/usr/bin/perluse strict;m
巡检类工作经常会出具日报,最近在原有日报的基础上又新增了一个表的数据量统计日报,主要是针对数据库中使用较频繁,数据量又较大的31张表。该日报有两个sheet组成,第一个sheet是数据填写,第二个sh
在实际生产环境中,常常需要从后台日志中截取报文,报文的形式类似于.........一个后台日志有多个报文,每个报文可由操作流水唯一确定。以前用AWK写过一个,程序如下:beginline=`awk &
最近写的一个perl程序,通过关键词匹配统计其出现的频率,让人领略到perl正则表达式的强大,程序如下:#!/usr/bin/perluse strict;my (%hash,%hash1,@arra
忍不住在 PerlChina 邮件列表中盘点了一下 Perl 里的 Web 应用框架(巧的是 PerlBuzz 最近也有一篇相关的讨论帖),于是乎,决定在我自己的 blog 上也贴一下 :) 原生 CGI/FastCGI 的 web app 对于较小的应用非常合适,但稍复杂一些就有些痛苦,但运行效率是最高的 ;) 如果是自己用 Perl 开发高性能的站,多推荐之。 Catalyst, CGI::A
bless有两个参数:对象的引用、类的名称。 类的名称是一个字符串,代表了类的类型信息,这是理解bless的关键。 所谓bless就是把 类型信息 赋予 实例变量。 程序包括5个文件: person.pm :实现了person类 dog.pm :实现了dog类 bless.pl : 正确的使用bless bless.wrong.pl : 错误的使用bless bless.cc : 使用C++语言实
gb2312转Utf的方法: use Encode; my $str = "中文"; $str_cnsoftware = encode("utf-8", decode("gb2312", $str));   Utf转 gb2312的方法: use Encode; my $str = "utf8中文"; $str_cnsoftware = encode("gb2312", decode("utf-8
  perl 计算硬盘利用率, 以%来查看硬盘资源是否存在IO消耗cpu资源情况; 部份代码参考了iostat源码;     #!/usr/bin/perl use Time::HiRes qw(gettimeofday); use POSIX; $SLEEPTIME=3; sub getDiskUtl() { $clock_ticks = POSIX::sysconf( &POSIX::_SC_
1 简单变量 Perl 的 Hello World 是怎么写的呢?请看下面的程序: #!/usr/bin/perl print "Hello World" 这个程序和前面 BASH 的 Hello World 程序几乎相同,只是第一行换成了 #!/usr/bin/perl ,还有显示的时候用的是 print,而不是 echo。有了前面 BASH 基础和 C 语言的基础,许多 Perl 的知识可以很
本文介绍Perl的Perl的简单语法,包括基本输入输出、分支循环控制结构、函数、常用系统调用和文件操作,以及进程管理几部分。 1 基本输入输出 在 BASH 脚本程序中,我们用 read var 来实现从键盘的输入,用 echo $var 来实现输出。那么在 Perl 中将有一点变化。Perl 中将标准输入用关键词 表示;标准输出用 表示,标准错误输出用 表示。故而从标准输入读取数据可以写成: $
正则表达式是 Perl 语言的一大特色,也是 Perl 程序中的一点难点,不过如果大家能够很好的掌握他,就可以轻易地用正则表达式来完成字符串处理的任务,当然在 CGI 程序设计中就更能得心应手了。下面我们列出一些正则表达式书写时的一些基本语法规则。 1 正则表达式的三种形式 首先我们应该知道 Perl 程序中,正则表达式有三种存在形式,他们分别是: 匹配:m/<regexp>/ (还可以简写为 /
在学习Perl和Shell时,有很多人可能会问这样一个问题,到底先学习哪个或者学习哪个更好! 每个人都有自己的想法,以下是个人愚见,请多多指教! Perl是larry wall为解决日常工作中的一个编程问题而产生的,它最初的主要功能是用于分析基于文本的数据和生成这些数据的统计和结果;尽管初衷很简单,但是后来发展了很多特点: 1、Perl是一种借鉴了awk、C、sed、shell、C++、Java等
Perl 有很多命令行参数. 通过它, 我们有机会写出更简单的程序. 在这篇文章里我们来了解一些常用的参数. (重点提示:在window下执行命令行程序的方式为 : perl -e "some code", 注意:是双引号啊,不是单引号,linux下执行时单引号) Safety Net Options 在使用 Perl 尝试一些聪明( 或 stupid) 的想法时, 错误难免会发生. 有经验的 P
转自: http://bbs.chinaunix.net/thread-1191868-1-1.html# 让你的perl代码看起来更像perl代码,而不是像C或者BASIC代码,最好的办法就是去了解perl的内置变量。perl可以通过这些内置变量可以控制程序运行时的诸多方面。 本文中,我们一起领略一下众多内置变量在文件的输入输出控制上的出色表现。 行计数 我决定写这篇文章的一个原因就是,当我发现
2009-02-02 13:07 #!/usr/bin/perl # D.O.M TEAM - 2007 # anonyph; arp; ka0x; xarnuz # 2005 - 2007 # BackConnectShell + Rootlab t00l # priv8! # 3sk0rbut0@gmail.com # # Backconnect by data cha0s (modifica
转自: http://bbs.chinaunix.net/thread-1191868-1-1.html# 让你的perl代码看起来更像perl代码,而不是像C或者BASIC代码,最好的办法就是去了解perl的内置变量。perl可以通过这些内置变量可以控制程序运行时的诸多方面。 本文中,我们一起领略一下众多内置变量在文件的输入输出控制上的出色表现。 行计数 我决定写这篇文章的一个原因就是,当我发现
黑莓 手机 屏幕发展历程对比 blackberry 各型号屏幕大小   黑莓手 机 一直在不断发展且新机型 也在不断上市. 因此,不同黑莓机型的屏幕分辨率也在不断变化着. 总的来说,屏幕分辨率一直在提高并且越来越清晰.我们对所有的黑莓 机型的屏幕分辨率做了个对比.~51blackberry ~com     可能大家特别感兴趣是新发布的黑莓机型,它的分辨率也是黑莓 机型中前所未有的.   黑莓 b
      公司里没有我用惯的UltraEdit的lisence了, 只能无奈转向开源的Notepad++, 找了半天才知道配置运行Perl的办法。         1,用Notepad++打开.pl文件,         2, F5或者Run->Run,打开运行窗口,在下面的框框里输入:Perl -w "$(FULL_CURRENT_PATH)", 然后Save,保存成一个命令就行,名字比如叫R