有人能解释一下这个 Perl 代码片段吗?
这段小代码一直是我的一堆脚本中的主要内容,但我从其他人编写的另一个工作脚本中获取了语法,并对其进行了调整以满足我的需求。我什至不确定这里使用的语法是打开文件处理程序的最佳或最常见的方法。
代码是:
$fh = \*STAT_FILE;
open ($fh,">>".$stat_file) or die "Can't open $stat_file: $!\n";
my $print_flag = ( -z $stat_file );
我不完全理解上面代码的第一行和最后一行。具体来说,分别是 \*STAT_FILE
和 -z
。
我知道,在大多数情况下,第二行将打开一个文件以进行追加或退出并抛出错误。但同样,我也不明白 $!
在该行中的用途是什么。
有人可以用伪代码向我逐行解释这个 Perl 代码吗?另外,如果上述方法不是首选方法,那么什么是?
提前致谢
This little piece of code has been a staple in a bunch of my scripts, but I took the syntax from another working script that someone else wrote and adapted it to fit my needs. I'm not even sure that the syntax used here is the best or most common way to open a file handler either.
The code is:
$fh = \*STAT_FILE;
open ($fh,">>".$stat_file) or die "Can't open $stat_file: $!\n";
my $print_flag = ( -z $stat_file );
I don't fully understand the first line and also the last line of the code above. Specifically, \*STAT_FILE
and -z
, respectively.
I know that, for the most part, the second line will open a file for appending or quit and throw an error. But again, I don't understand what purpose the $!
serves in that line either.
Can someone explain this Perl code, line-by-line, to me in pseudo? Also, if the method above is not the preferred method, then what is?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 perl 5.6 之前,文件句柄只能是 glob(裸字)或对 glob 的引用(这就是 \*STAT_FILE)。另外,最好使用 3 参数打开(请参阅文档。另请参阅perlopentut)。所以你现在可以这样做:
忘记 \*STAT_FILE。
-z 是文件测试函数之一(并采用文件名或文件句柄作为参数)并测试文件大小是否为零。
$!是特殊变量之一,包含最新的系统错误消息(在这种情况下,为什么您可以打不开文件,可能是权限问题,或者文件路径中的目录不存在等)。
你应该学习使用perldoc,所有这些都在perldoc中:
perldoc perlfunc(特别是perldoc -f open和perldoc -f -X)
perldoc perlvar
Before perl 5.6, file handles could only be globs (bare words) or references to globs (which is what \*STAT_FILE is). Also, it's better to use 3-argument open (See the docs. Also see perlopentut). So you can now do:
and forget about \*STAT_FILE.
-z is one of the file test functions (and takes a file name or file handle as an argument) and tests to see if the file has zero size.
$! is one of the Special Variables and contains the most recent system error message (in this case why you can not open the file, perhaps permission issues, or a directory in the path to the file does not exist, etc.).
You should learn to use perldoc, all of this is in perldoc:
perldoc perlfunc (specifically perldoc -f open and perldoc -f -X)
perldoc perlvar
第一行向变量分配对 typeglob(完整符号表条目)STAT_FILE 的引用(反斜杠符号)。这是一个非常惯用的 Perl 构造,用于传递文件句柄,如 Larry Wall“Programming Perl”中所报道的那样,仅举其名称。美元!变量包含操作系统返回的错误消息。
所以整个意思是:
The first row assign to the variable a reference (the backslash sign) to the typeglob (a fullsymbol table entry) STAT_FILE. This has been a quite idiomatic perl construct to pass filehandles as reported, just to name it, in the Larry Wall "Programming perl". The $! variable contains the error message reurned by the operating system.
So the whole meaning is: