⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 perlprogramingprimer.txt

📁 perl编程初级教程! 详细的讲解了
💻 TXT
📖 第 1 页 / 共 2 页
字号:
第一页:一个最简单的Perl程序

这里是我们开始的一个基本的perl程序:
#!/usr/local/bin/perl
#
# Program to do the obvious
#
print 'Hello world.';		# Print a message

我们将对其中的每个部分进行讨论。

第一行:

每个perl程序的第一行都是:

#!/usr/local/bin/perl

- 虽然随着系统的不同而不同。这行告诉机器当文件执行时该怎么做(即告诉它通过Perl运行这个文件)。

注释和语句:

用#符号可以在程序中插入注释,并且从#开始到这行结尾都被忽略(除了第一行)。把注释扩展到几行的唯一办法是在每行前都用#符号。

Perl中的语句必须在结尾加一个分号,象上面程序中最后一行那样。

简单的打印:

print函数输出一些信息。在上面的例子中它打印出字符串Hello world,当然这行也以分号结束。

你可能会发现上面的程序会产生一个有点意想不到的结果,那么就让我们运行它吧。

第二页:运行程序

用文本编辑器敲入这个例子程序,然后保存之。Emacs是一个很好的编辑器,但是你可以使用任何习惯的文本编辑器。

然后用下面的命令使这个文件可执行。

chmod u+x progname 

在UNIX提示符下,progname是程序的文件名。现在可以运行这个程序 - 在提示符下运行下面任何一种命令:

perl progname ./progname progname 

如果有错误,将会得到错误信息,或者什么也得不到。可以用

warning参数运行程序:

perl -w progname 

这会在试图执行程序前显示警告和其它帮助信息。用调试器运行程序可以使用命令:

perl -d progname 

当执行程序时,Perl首先编译之,然后执行编译后的版本。于是在经过编辑程序后的短暂停顿后,这个程序会运行得很快

第三页:标量

Perl中最基本的变量是标量。标量可以是字符串或数字,而且字符串和数字可以互换。例如,语句

$priority = 9;

设置标量$priority为9,但是也可以设置它为字符串:

$priority = 'high';

Perl也接受以字符串表示的数字,如下:

$priority = '9'; $default = '0009'; 

而且可以接受算术和其它操作。

一般来说,变量由数字、字母和下划线组成,但是不能以数字开始,而且$_是一个特殊变量,我们以后会提到。同时,Perl是大小写敏感的,所以$a和$A是不同的变量。

操作符和赋值语句:

Perl使用所有的C常用的操作符:
$a = 1 + 2;	# Add 1 and 2 and store in $a
$a = 3 - 4;	# Subtract 4 from 3 and store in $a
$a = 5 * 6;	# Multiply 5 and 6
$a = 7 / 8;	# Divide 7 by 8 to give 0.875
$a = 9 ** 10;	# Nine to the power of 10
$a = 5 % 2;	# Remainder of 5 divided by 2
++$a;		# Increment $a and then return it
$a++;		# Return $a and then increment it
--$a;		# Decrement $a and then return it
$a--;		# Return $a and then decrement it
对于字符串,Perl有自己的操作符: 
$a = $b . $c;	# Concatenate $b and $c
$a = $b x $c;	# $b repeated $c times
Perl的赋值语句包括: 
$a = $b;	# Assign $b to $a
$a += $b;	# Add $b to $a
$a -= $b;	# Subtract $b from $a
$a .= $b;	# Append $b onto $a

其它的操作符可以在perlop手册页中找到,在提示符后敲入man perlop。

互操作性:

下面的代码用串联打印apples and pears:
$a = 'apples';
$b = 'pears';
print $a.' and '.$b;

最后的打印语句中应该只包含一个字符串,但是:

print '$a and $b'; 

的结果为$a and $b,不是我们所期望的。 

不过我们可以用双引号代替单引号:

print "$a and $b";

双引号强迫任何代码的互操作,其它可以互操作的代码包括特殊符号如换行(\n)和制表符(\t)。
第一页:数组变量

数组变量是标量的集合。数组变量与标量有相同的形式,除了其前缀为@符号。下面的语句把三个元素赋给数组变量@food,把两个元素赋给数组变量@music。

数组通过以0开始的索引进行访问,方括号内为索引值。表达式

$food[2]

返回的结果为ells。注意上式中为$,而不是@,因为其引用的是一个标量。

数组赋值

在Perl中,相同的表达式在不同的上下文中会产生不同的结果。下面的第一个赋值语句引用了@music变量,所以结果与第二个赋值语句相同。

这也是把元素加入数组的一种方式。一种更简洁的把元素加入数组的方式是:

push(@food,"eggs");

- 把eggs推入数组@food的结尾。把两个或更多元素推入数组可以用下面方式中的一种:
push(@food, "eggs", "lard");
push(@food, ("eggs", "lard"));
push(@food, @morefood);

push函数返回新的列表的长度。

可以用pop函数移去一个列表中的最后一个元素,然后返回这个元素。在最初的列表中,pop函数返回eels,然后@food中有两个元素:

$grub = pop(@food); # Now $grub = "eels"

也可以把数组赋给一个标量。通常上下文是很重要的。$f=@food;得到@food的长度,但是$f="@food";把列表转换成以空格隔开每个元素的字符串。通过改变特殊变量$"的值可以把空格用其它任何字符串代替。这个变量只是Perl中很多特殊变量中的一个,它们中的很多都有奇怪的名字。

数组也可以用来为多个标量进行赋值:
($a, $b) = ($c, $d);		# Same as $a=$c; $b=$d;
($a, $b) = @food;		# $a and $b are the first two
				# items of @food.
($a, @somefood) = @food;	# $a is the first item of @food
				# @somefood is a list of the
				# others.
(@somefood, $a) = @food;	# @somefood is @food and
				# $a is undefined.

最后一个赋值语句的发生是因为数组是贪婪的,@somefood会吞掉@food中的任何值。因此应尽量避免这种方式。

最后,你可能想知道列表中最后一个元素的索引值,可以用这个表达式:$#food。

打印数组:

既然上下文很重要,就不要奇怪下面的表达式产生不同的结果:
print @food;	# By itself
print "@food";	# Embedded in double quotes
print @food."";	# In a scalar context
第二页:文件处理

下面是一个简单的perl程序,与UNIX中cat命令对某个文件的操作相同。
#!/usr/local/bin/perl
#
# Program to open the password file, read it in,
# print it, and close it again.

$file = '/etc/passwd';		# Name the file
open(INFO, $file);		# Open the file
@lines = <INFO>;		# Read it into an array
close(INFO);			# Close the file
print @lines;			# Print the array

open函数打开一个文件并进行读操作。第一个参数filehandle是指向文件的句柄。第二个参数为被打开的文件的文件名。如果文件名以被引号包围的形式给出,那么它只被从字面意义上引用,而没有shell解释。

因此表达式'~/notes/todolist'不会被成功地翻译。如果希望得到shell解释,可以使用尖括号:即使用<~/notes/todolist>。

close函数告诉Perl关闭被打开的文件。

open语句也可以对文件进行输出和附加操作。可以在文件名前加>进行输出操作,用>>进行附加操作:
open(INFO, $file);	# Open for input
open(INFO, ">$file");	# Open for output
open(INFO, ">>$file");	# Open for appending
open(INFO, "<$file");	# Also open for input

如果想在一个已经打开的文件中打印信息,可以用带参数的打印语句。把一个字符串打印到一个用INFO句柄打开的文件中可以使用

print INFO "This line goes to the file.\n";

可以用下面的语句打开标准输入(通常为键盘)和标准输出(通常为屏幕):
open(INFO, '-');	# Open standard input
open(INFO, '>-');	# Open standard output

在上面的程序中从一个文件中读取信息。这个文件是INFO,Perl用尖括号对它进行读操作。因此语句

@lines=<INFO>;

把文件中的所有信息读入数组@lines中。如果用标量$lines,则只读第一行。在这两种情况下,每行都以换行符结束.
第三页:控制结构

Perl支持很多种与C类似的控制结构,但是也与Pascal很相似。下面我们分别对着这些结构进行讨论。

foreach

Perl使用foreach结构对数组或其它列表结构中的每行进行操作:
foreach $morsel (@food)		# Visit each item in turn
				# and call it $morsel
{
	print "$morsel\n";	# Print the item
	print "Yum yum\n";	# That was nice
}

每次的操作过程被包围在花括号内。程序块中的$morsel第一次被赋予@food数组中的第一个值,然后被赋予数组的第二个值,依次类推。如果@food是空的,那么程序块将不会被执行。

判断

判断是检验表达式结果是真是假的一种结构。在Perl中,任何非0数字和非空字符串被看作真。数字0、0字符串和空字符串被看作假。下面是一些基于数字和字符串的判断:
$a == $b		# Is $a numerically equal to $b?
			# Beware: Don't use the = operator.
$a != $b		# Is $a numerically unequal to $b?
$a eq $b		# Is $a string-equal to $b?
$a ne $b		# Is $a string-unequal to $b?

也可以用逻辑与、或、非: 
($a && $b)		# Is $a and $b true?
($a || $b)		# Is either $a or $b true?
!($a)			# is $a false?

for

Perl的for结构与C的类似:
for (initialise; test; inc)
{
	 first_action;
	 second_action;
	 etc
}

语句initialise被首先执行,然后当test为真时程序块被执行。程序块每执行一次,inc发生一次。下面是一个循环打印数字0到9的循环:
for ($i = 0; $i < 10; ++$i)	# Start with $i = 1
				# Do it while $i < 10
				# Increment $i before repeating
{
	print "$i\n";
}

while和until

下面是一个从键盘读输入,知道口令正确为止的程序:
#!/usr/local/bin/perl
print "Password? ";		# Ask for input
$a = <STDIN>;			# Get input
chop $a;			# Remove the newline at end
while ($a ne "fred")		# While input is wrong...
{
    print "sorry. Again? ";	# Ask again
    $a = <STDIN>;		# Get input again
    chop $a;			# Chop off newline again
}

当键盘输入与口令不同时花括号内的程序块被执行。while结构很清晰,但有几点要注意:第一,我们可以从标准输入读入信息,而不用打开文件。第二,当口令被输入时,$a被赋予包括换行符在结尾的值。chop函数删除字符串的最后一个字符,这里是换行符。

until也可以执行相同的工作。程序块被反复执行,直到表达式为真。

另一种方式是把while或until放在程序块的后面。这要求do放在程序块的开始处,而判断在结尾处。这样程序可以这样写:
#!/usr/local/bin/perl
do
{
	"Password? ";		# Ask for input
	$a = <STDIN>;		# Get input
	chop $a;		# Chop off newline
}
while ($a ne "fred")		# Redo while wrong input

Perl初级教程 - 第三天

第一页:条件语句

Perl当然也支持if/then/else语句,下面是一个例子:
if ($a)
{
	print "The string is not empty\n";
}
else
{
	print "The string is empty\n";
}

记住,空字符串被认为是false,如果$a是字符串"0",结果将是"empty"。

条件语句中也可以使用elsif:
if (!$a)			# The ! is the not operator
{
	print "The string is empty\n";
}
elsif (length($a) == 1)		# If above fails, try this
{
	print "The string has one character\n";
}
elsif (length($a) == 2)		# If that fails, try this
{
	print "The string has two characters\n";
}
else				# Now, everything has failed
{
	print "The string has lots of characters\n";
}

注意:elsif中确实缺一个"e"。
第二页:字符串匹配

Perl的最有用的特征之一是

它的强大的字符串处理能力。其中的核心是被很多其它UNIX工具使用的规则表达式(regular expression - RE)。

规则表达式

规则表达式包含在斜线内,匹配通过=~操作符进行。如果字符串the出现在变量$sentence中,则下面的表达式为真:

$sentence =~ /the/

RE是大小写敏感的,所以如果

$sentence = "The quick brown fox";

那么上面的匹配结果为false。操作符!~用在“非匹配”时,在上面的例子中

$sentence !~ /the/

是真,因为字符串the没有出现在$sentence中。

特殊变量$_

在条件语句
if ($sentence =~ /under/)
{
	print "We're talking about rugby\n";
}

中,如果我们有下面两个表达式中的一个:
$sentence = "Up and under";
$sentence = "Best winkles in Sunderland";

将打印出一条信息。

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -