问题
package MY_TEST;
use warnings;
use strict;
use Win32::Console;
my $out = Win32::Console->new( STD_OUTPUT_HANDLE );
sub test_print {
$out->Write( "printed with 'Write'\n" );
print( "printed with 'print'\n" );
}
When I call this package with this script
#!/usr/bin/env perl
use warnings;
use strict;
use 5.10.0;
use FindBin qw($RealBin);
use MY_TEST;
say 'Before "test_print"';
MY_TEST::test_print;
say 'After "test_print"';
the output looks like this
Before "test_print"
printed with 'Write'
printed with 'print'
After "test_print"
But when I comment the Write line out
# $out->Write( "printed with 'Write'\n" );
the output is empty.
Why does removing the Write line prevent printing the print lines?
回答1:
Just a guess, but it could be related to needing to flush the buffer. Write() might do it while print() naturally will not.
回答2:
I do not know the reason, but I can replicate the behavior under Windows XP SP3 with ActiveState's perl 5.16.3.
On a hunch, I made the following change in MY_TEST.pm:
my $out;
sub test_print {
$out ||= Win32::Console->new( STD_OUTPUT_HANDLE );
# $out->Write( "printed with 'Write'\n" );
print( "printed with 'print'\n" );
}
And I got the output:
Before "test_print" printed with 'print' After "test_print"
Interesting …
This has something to do with the which phase of the execution of the script the handle gets assigned/resolved, but I can't quite put my finger on it right now.
来源:https://stackoverflow.com/questions/18387181/win32console-and-stdout