我有两个关于Perl open函数的问题:
1)我似乎记得Perl最佳实践中的3参数版本open比两个参数版本更好,例如
open(OUT, '>>', $file);
Run Code Online (Sandbox Code Playgroud)
与
open(OUT, ">>$file");
Run Code Online (Sandbox Code Playgroud)
这是为什么?我试图告诉别人前几天使用3参数版本,但似乎无法用任何东西支持它.
2)我似乎还记得autovivified文件句柄比bareword文件句柄更受青睐(他们称之为不同的东西)?而且也记不住为什么,例如
open(my $out, '>>', $file);
Run Code Online (Sandbox Code Playgroud)
与
open(OUT, '>>', $file);
Run Code Online (Sandbox Code Playgroud)
这是strict件事吗?我似乎记得能够使用OUT,strict但我不记得了.
#!/usr/local/bin/perl
sub trial
{
open (LOGFILE, 'C:\Users\out.txt');
trial();
}
trial();
Run Code Online (Sandbox Code Playgroud)
请忽略它将进入无限循环.
文件句柄LOGFILE是本地方法还是私有方法?如果不是,我该如何将其设为私有/本地?我知道我的.但我不知道如何在文件句柄上使用它.
我有这个代码在dir中创建一个.txt文件列表,并在输出文件中的2列中打印出来; 所以我只想避免在最后一个文件之后的新行(\n)
#!/usr/bin/perl -w
use strict;
use Getopt::Long;
#Variables
my ($dir_path, $outputfile);
GetOptions (
'dir=s' =>\$dir_path,
'list=s' =>\$outputfile
);
opendir (DIR, $dir_path) or die $!;
open LIST, '>', $outputfile, or die "can´t open $outputfile file";
while (my $files=readdir(DIR)) {
chomp $files;
if ($files =~ m/\.txt$/g) {
print LIST "$files\t$files\n";
}
else {
next;
}
}
closedir DIR;
close LIST;
exit;
Run Code Online (Sandbox Code Playgroud)
它打印:
file_1.txt file_1.txt
file_2.txt file_2.txt
file_3.txt file_3.txt
file_Last.txt file_Last.txt
NEW_LINE (\n)
Run Code Online (Sandbox Code Playgroud)
我只想避免在最后一个文件后打印las NEW LINE !!!:
file_1.txt file_1.txt
file_2.txt file_2.txt
file_3.txt …Run Code Online (Sandbox Code Playgroud)