tcl - TCL:打开一个文件并返回一个包含注释和空行的非空行列表
问题描述
我有一些旧的 perl 代码可以打开一个包含文件列表的文件并将文件作为列表返回。此外,此文件列表可以包含空白行和注释,以使文件列表更具可读性,但这些文件已从过程返回的最终列表中删除,请参见下面的示例。我如何将其转换为 TCL 程序?
# PERL VERSION
sub load_file_list() {
my $file_list = shift;
print "load_file_list: $file_list\n";
my @ret = ();
open(F, "$file_list") || die("could not open file: $file_list\n");
while(<F>) {
my $line = $_;
$line =~ s/\r//g; # remove CR
chomp($line); # remove LF
$line =~ s/\/\/.*$//; # remove '//' comments
$line =~ s/#.*$//; # remove '#' comments
next if ($line =~ /^\s*$/); # remove blank lines
while($line =~ /\$(\w+)\b/) {
my $avar = $1;
$line =~ s/\$${avar}\b/${${avar}}/g;
#print "$line\n";
push(@ret, $line);
}
}
close(F);
return @ret;
}
解决方案
这更像是 1:1 的翻译
proc load_file_list {file_list} {
# I don't like hardcoding the proc name
set procname [lindex [info level 0] 0]
puts "$procname: $file_list"
set ret {}
try {
set fh [open $file_list]
} on error e {
error "coult not open file $file_list: $e"
}
while {[gets $fh line] != -1} {
set line [regsub -all {\r} $line ""] # remove CR
# no need to chomp, gets removes the newline
set line [regsub {//.*} $line ""] # remove // comments
set line [regsub {#.*} $line ""] # remove # comments
if {[string trim $line] eq ""} then continue # remove blank lines
# expand variables in the line
# executing in the calling scope, presumably the variables are in scope there
set line [uplevel 1 [list subst -nocommands -nobackslashes $line]]
lappend ret $line
}
close $fh
return $ret
}
推荐阅读
- bots - Telegram bot,是否可以确保图像不是从图库中挑选的
- javascript - 如何在使用 Typescript 的反应测试库中使用 setState 测试反应组件
- sql - 返回某个参数以下的最大值
- vb.net - SnmpSharpNet 和 Get 在列表中使用一个错误的 OID
- c# - cmd.exe 和 adb 命令
- spring-boot - Cassandra / Spring boot 错误:协议初始化请求,第 1 步(选项):发送请求失败(java.nio.channels.NotYetConnectedException))
- javascript - 使用 MediaRecorder 时如何在 getUserMedia 和 getDisplayMedia 之间转换?
- reactjs - 在没有上下文的情况下反应自定义身份验证钩子
- java - 列表中的列表。标准 API
- mysql - 在 MySQL 中计算一个时间间隔内的平均值总和