首页 > 解决方案 > 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;
}

标签: tcl

解决方案


这更像是 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
}

推荐阅读