Win32::Console and STDOUT

穿精又带淫゛_ 提交于 2019-12-13 04:37:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!