(d) Variable Localization:my or local
通常我们在程序中定义的变量都是全域变量,所以在子程序中若要把变量区域化则要加上 my 或 local 关键词,例如:my $x=3;,若子程序所用的变量名不小心和主程相同,Perl会以目前正在执行的子程序里的变量为优先。
4 I/O和档案处理
(a) Syntax:
open(FILEHANDLE,"Expression");
close(FILEHANDLE);
这里的Expression是一个叙述加上文件名称,若Expression只有文件名称没有加上叙述,则预设是只读。Expressions叙述如下:
Expression Effect
open(FH, " filename")
open(FH, "+filename")
open(FH, ">filename") Opens filename for writing.
open(FH, "+>filename") Opens filename for both reading and writing.
open(FH, ">>filename") Appends to filename.
open(FH, "command|") Runs the command and pipes its output to thefilehandle.
open(FH, "command|") Pipes the output along the filehandle to thecommand.
open(FH, "-") Opens STDIN.
open(FH, ">-") Opens STDOUT.
open(FH, "<&=N") Where N is a number, this performs the equivalent of C'sfdopen for reading.
open(FH, ">&=N") Where N is a number, this performs the equivalent of C'sfdopen for writing.
例:
# 开启$filename这个档案,若开启失败则印出die后面的讯息,并结束程序。
open(FILE, $filename) || die "Can't open file $filename : $!n";
# 下面是一个十分精简的写法,和 while($_=){print "$_";} 是等效的。
print while();
# 档案开启后要记得随手关闭,这才是写程序的好习惯。
close(FILE);
# $!和$_都是Perl的特殊变数,下面会介绍的。
(b) Input:
Perl没有特别用来输入的函数,因为Perl在执行程序时,会自动开启标准输入装置,其filehandle定为STDIN,所以在Perl中要输入数据的方法就是使用:
# Perl不会自动去掉结尾的CR/LF,跟C语言不同,所以要用chomp函数帮你去掉它。
# 大家常常会忘记这个动作,导致结果跟你想的不一样,要特别注意一下。
$input=<STDIN>; chomp $input;
# 下面是较简洁的写法。
chomp($input=<STDIN>);
(c) Output:print "variables or 字符串";
Perl也有printf()函数,语法和C语言一模一样,我就不多做介绍了。Perl另外有个print函数,比printf()更方便、更好用,包你爱不释手。Output不外乎是输出到屏幕或档案,用例子来说明比较容易了解。
# 不用再指定变量的data type,这样不是比printf()方便多了吗?
print "Scalar value is $xn";
# . 是字符串加法的运算子,上下这两行是等效的。
print "Scalar value is " . $x . "n";
# 输出到档案的方法。
print FILE "print $x to a file.";









