Color output problems in cmd
Here is the code:
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 );
};
}
The problem I have is with the way output gets colored. What I am expecting to get is "some directory" in green on black background. Instead I get background color in green and text in black, sometimes white randomly. I have this problem on every other code where I use color(). I noticed the problem goes away after I restar开发者_如何学Ct. Also, my suspicion is that the problem returns affecting DOS and all its windows when I run some other perl code. Basically, once it goes wrong it is there until restart for every instance of color(). It looks like a glitch. Please help.
I do not observe the problem. However, the fact that you are using system
(which starts a different shell to carry out the command and therefore really does not change your directory) may be what's interfering. Alternatively, the console might be left in an indeterminate state if you are using CTRL-C to break out of the script.
Here is a better way of accomplishing what you want:
#!/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': $!";
}
精彩评论