1

这是代码:

use Cwd;
use Win32::Console::ANSI;# installed module with ppm
use Term::ANSIColor;

$parent =  cwd();

@files = <*>;
print "\n";
foreach (@files)
{
    $child = "$parent/$_";
    if (-f $_){print "$child\n";}; #file test
    if (-d $_)#directory test
    {
        print color("green")."$child/\n".color("reset");
        my($command) = "cd $child/";#submerge one directory down ( recursive here?)
        $command=~s/\//\\/g;
        system( $command );
    };
}

我遇到的问题是输出着色的方式。我期望得到的是黑色背景上的绿色“某个目录”。相反,我得到绿色的背景颜色和黑色的文本,有时是随机的白色。我在使用 color() 的所有其他代码上都有这个问题。我注意到重新启动后问题消失了。另外,我怀疑当我运行其他一些 perl 代码时,问题会再次影响 DOS 及其所有窗口。基本上,一旦出现问题,它就会一直存在,直到重新启动 color() 的每个实例。它看起来像一个小故障。请帮忙。

4

1 回答 1

0

我没有观察到问题。但是,您正在使用的事实system(它启动不同的 shell 来执行命令,因此实际上不会更改您的目录)可能是干扰因素。CTRL-C或者,如果您使用中断脚本,控制台可能会处于不确定状态。

这是完成您想要的更好的方法:

#!/usr/bin/perl

use Cwd;
use File::Spec::Functions qw( catfile canonpath );
use Win32::Console::ANSI;
use Term::ANSIColor;

local $SIG{INT} = sub { print color('reset') };

my $top = cwd;

print_contents($top);

sub print_contents {
    my ($dir) = @_;

    opendir my $dir_h, $dir
        or die "Cannot open directory: '$dir': $!";

    while ( defined (my $entry = readdir $dir_h) ) {
        next if $entry =~ /^[.][.]?\z/;
        my $path = canonpath catfile $dir => $entry;
        if ( -f $path ) {
            print "$path\n";
        }
        elsif ( -d $path ) {
            print color('green'), $path, color('reset'), "\n";
            print_contents($path);
        }
    }

    closedir $dir_h
        or die "Cannot close directory: '$dir': $!";
}
于 2010-12-22T17:59:56.840 回答