gpt4 book ai didi

perl - 本地化 "$|"

转载 作者:行者123 更新时间:2023-12-02 07:03:43 27 4
gpt4 key购买 nike

我可以同时使用这两种方法来本地化 $| 还是我应该使用其中一种来支持另一种?

方法一:备份“_init_scr”中$|的旧值,并在调用“_end_win”时将$|设置回旧值。方式 2:调用 local $| = 1 在调用“_init_scr”之后。

package Package_name

# ...

sub _init_scr {
my ( $arg ) = @_;
$arg->{old_handle} = select( $arg->{handle_out} );
#$arg->{backup_flush} = $|; # way 1
$| = 1;
# ...
}

sub _end_win {
my ( $arg ) = @_;
# ...
#$| = $arg->{backup_flush}; # way 1
select( $arg->{old_handle} );
}

sub choose {
my $arg = ...;
# ...
_init_scr( $arg );
# way 2 - instead of setting `$|` in "_init_scr" set it here:
#local $| = 1;
# ...
while ( 1 ) {
my $c = _getch( $arg );
# ...;
given ( $c ) {
# ...
when ( $c == CONTROL_C ) {
_end_win( $arg );
print "^C";
kill( 'INT', $$ );
return;
}
when ( $c == KEY_ENTER ) {
# ...
_end_win( $arg );
return $result;
}
}
}
}

最佳答案

使用本地。这样,无论 sub 以何种方式退出(异常、提前 return 等),$| 都会被恢复。

顺便说一下,您可以使用 select()->flush; 而不是来回切换 $|

use IO::Handle qw( );  # Required in older versions of Perl.
print "^C";
select()->flush();

也就是说,local $| 的优势消失了,因为无论如何您都需要调用 _end_win 来清理。因此,让我们摆脱对 _end_win 的需求。

use Sub::ScopeFinalizer qw( scope_finalizer );

sub _local_scr {
my ( $arg ) = @_;
my $old_autoflush = $|;
my $old_handle = select( $arg->{handle_out} );
$| = 1;

return scope_finalizer {
$| = $old_autoflush;
select($old_handle);
};
}

sub choose {
my $arg = ...;

my $guard = _local_scr( $arg );

while ( 1 ) {
...
print "^C";
kill( 'INT', $$ );
return;
...
}
}

关于perl - 本地化 "$|",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16039907/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com