时间: 2021-07-31 作者:daque
一、翻开、封闭文献 语法为open (filevar, filename),个中filevar为文献句柄,大概说是步调顶用来代办某文献的代号,filename为文献名,其路途可为对立路途,亦可为一致路途。open(file1,"file1");open(file1, "/u/jqpublic/file1");翻开文献时必需确定考察形式,在perl中有三种考察形式:读、写和增添。后两种形式的辨别在乎写形式将原文献掩盖,原有实质丧失,情势为:open(outfile,">outfile");而增添形式则在原文献的结束处连接增添实质,情势为:open(appendfile, ">>appendfile")。要提防的是,不许对文献同声举行读和写/增添操纵。open的归来值用来决定翻开文献的操纵能否胜利,当其胜利时归来非零值,波折时归来零,所以不妨如次确定:if (open(myfile, "myfile")) {# here's what to do if the file opened successfully}当文献翻开波折时中断步调:unless (open (myfile, "file1")) {die ("cannot open input file file1\n");}亦可用论理或操纵符表白如次:open (myfile, "file1") || die ("could not open file"); 当文献操纵结束后,用close(myfile); 封闭文献。二、读文献 语句$line = ;从文献中读取一条龙数据保存到大略变量$line中并把文献南针向后挪动一条龙。为规范输出文献,常常为键盘输出,不须要翻开。语句@array = ;把文献的十足实质读入数组@array,文献的每一条龙(含回车符)为@array的一个元素。三、写文献 情势为:open(outfile, ">outfile");print outfile ("here is an output line.\n");注:stdout、stderr为规范输入和规范缺点文献,常常为屏幕,且不须要翻开。四、确定文献状况 1、文献尝试操纵符语法为:-op expr,如:if (-e "/path/file1") {print stderr ("file file1 exists.\n");}文献尝试操纵符
操纵符
刻画
-b
能否为块摆设
-c
能否为字符摆设
-d
能否为目次
-e
能否生存
-f
能否为普遍文献
-g
能否树立了setgid位
-k
能否树立了sticky位
-l
能否为标记链接
-o
能否具有该文献
-p
能否为弹道
-r
能否可读
-s
能否非空
-t
能否表白结尾
-u
能否树立了setuid位
-w
能否可写
-x
能否可实行
-z
能否为空文献
-a
距上回考察多长功夫
-b
能否为二进制文献
-c
距上回考察文献的inode多长功夫
-m
距上回窜改多长功夫
-o
能否只为“真实的用户”所具有
-r
能否惟有“真实的用户”可读
-s
能否为socket
-t
能否为文本文献
-w
能否惟有"真实的用户"可写
-x
能否惟有"真实的用户"可实行
注:“真实的用户”指登录时指定的userid,与当进步程用户id对立,吩咐suid不妨变换有功效户id。
例:unless (open(infile, "infile")) {die ("input file infile cannot be opened.\n");}if (-e "outfile") {die ("output file outfile already exists.\n");}unless (open(outfile, ">outfile")) {die ("output file outfile cannot be opened.\n");}等价于open(infile, "infile") && !(-e "outfile") &&open(outfile, ">outfile") || die("cannot open files\n");五、吩咐行参数 象c一律,perl也有保存吩咐行参数的数组@argv,不妨用来辨别处置各个吩咐行参数;与c各别的是,$argv[0]是第一个参数,而不是步调名自己。$var = $argv[0]; # 第一个参数$numargs = @argv; # 参数的个数perl中,<>操纵符本质上是对数组@argv的隐含的援用,其处事道理为:1、当perl证明器第一次看到<>时,翻开以$argv[0]为文献名的文献;2、执动作作shift(@argv); 即把数组@argv的元素向前挪动一个,其元素数目即缩小了一个。3、<>操纵符读取在第一步翻开的文献中的一切行。4、读完后,证明器回到第一步反复。例:@argv = ("myfile1", "myfile2"); #本质上由吩咐行参数赋值while ($line = <>) {print ($line);} 将把文献myfile1和myfile2的实质打字与印刷出来。六、翻开弹道 用步调的情势也不妨象吩咐行一律翻开和运用弹道(ex:ls > tempfile)。如语句open (mypipe, "| cat >hello"); 翻开一个弹道,发送给mypipe的输入变成吩咐"cat >hello"的输出。因为cat吩咐将表露输出文献的实质,故该语句等价于open(mypipe, ">hello"); 用弹道发送邮件如次:open (message, "| mail dave");print message ("hi, dave! your perl program sent this!\n");close (message);