perl script with AnyEvent is not going fast enough - perl

Here is the little script I created to do HTTP transactions from a file with a list of URLs. The problem is that it's not able to do HTTP transactions as fast as I would like. More precisely, I set the rate to be 200/seconds, but it was able to send only at about 50/second. The server is powerful enough to handle 100/second.
This was run on a powerful PC with E5-1650 CPU and 64GB of RAM running Ubuntu 14.04 desktop. When the script runs, the CPU usage is only about 12%. The command I used was perl httpStresser.pl urlList rate 200.
Any idea why?
use AnyEvent;
use EV;
use AnyEvent::HTTP;
use AnyEvent::Handle;
use Time::HiRes qw( gettimeofday );
my $expectedRespCode = 200;
my $rate = 1;
my #urls = ();
readUrls(shift);
my $numOfUrls = $#urls;
my $start = time();
my $printed = 0; #have we printed the completion msg.
my $gId = 0;
my $spawned;
my #ctx = ();
my $i;
for ($i=0; $i<=$#ARGV; $i++) {
if ($ARGV[$i] =~ /^expect/) {
$expectedRespCode = $ARGV[$i+1];
$i++;
} elsif ($ARGV[$i] =~ /^rate/) {
$rate = $ARGV[$i+1];
print "rate is now $rate\n";
$i++;
} elsif ($ARGV[$i] =~ /^skip/) {
$gId = $ARGV[$i+1];
$i++;
} else {
die "only max, stayup are supported\n";
}
}
my $spawned = 0;
my $w = AnyEvent->condvar;
$| = 1;
my $start = getTS();
my $_timer;
$_timer = AnyEvent->timer(after => 0, interval => 0.001, cb => ::timeoutHandler);
$w->recv;
sub kickoff {
my $id = $gId ++;
if ($id > $numOfUrls) {
if ($printed == 0) {
print "done!!\n"; $printed = 1;
}
return;
}
#print "$id\n";
http_get $urls[$id], headers => { }, sub {
my $statusCode = $_[1]->{Status};
#printf "status $statusCode %d\n", time() - $start;
if (($id % 100) == 0) {
print "$id\n";
}
if ($statusCode != $expectedRespCode) {
print "unexpected resp code $id:$statusCode $urls[$id]\n";
}
};
}
sub timeoutHandler {
#print time(), "|\n";
if (! defined $start) {
$start = getTS(); kickoff(); $spawned = 1; return;
}
my $delta = getTS() - $start;
my $target = $delta * $rate;
#printf "%.4f %4d $spawned\n", $delta, $target;
for (; $spawned <= $target; $spawned++) {
kickoff();
}
if ($delta >= 1.0 ) {
$start += 1.0; $spawned = 0;
}
}
sub readUrls {
my $fname = shift;
my $line;
open FD, $fname || die "Failed to open $fname $!\n";
while (<FD>) {
chomp($line = $_);
push #urls, $line;
}
close FD;
}
sub getTS {
my ($seconds, $microseconds) = gettimeofday;
return $seconds + (0.0+ $microseconds)/1000000.0;
}

Related

How to debug a script that will kill by system when await multi Promise?

Answer "the script used too much memory".
I start a few start to read text file line by line, and convert the text to blob, then send it to socket:
use experimental :pack;
sub heart-msg(Str $msg, Str $device-id --> Blob) {
my $heart-msg = $msg.substr(0, $msg.chars - 8);
my $header-buf = pack("H*", $heart-msg);
my $device-id-buf = pack("L*", $device-id);
$header-buf ~ $device-id-buf
}
sub deal-message(Str $msg, Str $device-id --> Blob) {
my $now = DateTime.now();
my $year = $now.year;
my $month = $now.month;
my $day = $now.day;
my $hour = $now.hour;
my $minute = $now.minute;
my $second = $now.second.Int;
my $check-number = 0;
my $head-msg = $msg.substr(0,4);
my $device-id-length = $msg.substr(4,2);
my $pf-code = $msg.substr(14, 2);
my $msg-length = $msg.substr(16, 4);
my $rel-time = $msg.substr(20, 4);
my $end-msg = $msg.substr(38, $msg.chars - 38 - 2);
my $head-msg-buf = pack("H*", $head-msg);
my $device-id-len-buf = pack("H*", $device-id-length);
my $device-id-buf = pack("L*", $device-id);
my $pf-code-buf = pack("H*", $pf-code);
my $msg-length-buf = pack("H*", $msg-length);
my $rel-time-buf = pack("H*", $rel-time);
my $year-buf = pack("S*", $year);
my $month-buf = pack("C*", $month);
my $day-buf = pack("C*", $day);
my $hour-buf = pack("C*", $hour);
my $minute-buf = pack("C*", $minute);
my $second-buf = pack("C*", $second);
my $end-msg-buf = pack("H*", $end-msg);
my #bufs = [$device-id-len-buf, $device-id-buf, $pf-code-buf, $msg-length-buf,
$rel-time-buf, $year-buf, $month-buf, $day-buf, $hour-buf, $minute-buf, $second-buf,
$end-msg-buf];
for #bufs -> $byte {
my $byte_sum = [+] $byte.contents;
$check-number += $byte_sum;
}
$check-number = $check-number % 256;
my $checked-msg-buf = pack("C*", $check-number);
[~] $head-msg-buf, |#bufs, $checked-msg-buf
}
sub deal-data(Str $msg, Str $device-id --> Blob) {
my $header = $msg.substr(0, 4);
given $header {
when '6868' {
return deal-message($msg, $device-id);
}
when '7468' {
return heart-msg($msg, $device-id);
}
default { return Buf.new }
}
}
sub MAIN(
:$host = '10.0.0.77',
Int() :$port = 4444,
Rat() :$interval = 0.001,
:$file = 'data.txt',
Int() :$device-num = 169) {
my $conn = IO::Socket::INET.new(:$host, :$port);
my #devices = "modelId.txt".IO.lines;
my #promises = gather for #devices[159..$device-num] -> $device-id {
take start {
my $f = lazy $file.IO.lines;
my $iterator = $f.iterator;
react {
whenever Supply.interval($interval) {
try {
my $line := $iterator.pull-one;
if $line =:= IterationEnd {
done;
} else {
my $blob = deal-data($line.chomp.split(/\s+/).tail, $device-id.Str);
#say $blob;
$conn.write($blob);
}
}
QUIT {
$conn.close;
say 'connecting closed';
default {
say .^name, '→ ', .Str;
say "handled in line $?LINE";
}
}
LAST {
say "Connection closed";
done;
}
}
}
}
}
await #promises;
}
When running on CentOS 7.4(12 core, 32G RAM), after a few seconds, my script was killed by system. When running on Win11(12 core, 16G RAM), it's OK.
So how to debug this script?

How do you modify font size in a running Gtk3 app?

I'm trying to find a way(the correct way) to modify the font size in a running Gtk3 Perl app using the Ctrl key plus mouse wheel. I can use the code below to modify the font-size but do you really have to use providers and styles to achieve this?
#! /usr/bin/env perl
use 5.26.1;
use local::lib;
use warnings;
use strict;
use utf8;
use constant MAX_FONT_SIZE => 200;
use constant MIN_FONT_SIZE => 12;
use Glib qw(TRUE FALSE);
use Gtk3 qw(init);
my $str = "label {font-size: ".MIN_FONT_SIZE."px;}";
sub getWheel {
my ($object, $event, $sp) = #_;
my ($ctrl, $mod) = #{$event->state};
my ($style, $provider) = #{$sp};
state $font_size = MIN_FONT_SIZE;
if ($ctrl eq q<control-mask> && $mod eq q<mod2-mask>) {
if ($event->direction eq q<up>) {
if ($font_size < MAX_FONT_SIZE) {
$font_size += 4;
$str = "label {font-size: ${font_size}px;}";
$provider->load_from_data ($str, length($str));
$style->add_provider($provider, 600);
}
}elsif ($event->direction eq q<down>){
if ($font_size > MIN_FONT_SIZE) {
$font_size -= 4;
$str = "label {font-size: ${font_size}px;}";
$provider->load_from_data ($str, length($str));
$style->add_provider($provider, 600);
}
}
}
FALSE;
}
my $window = Gtk3::Window->new(q<toplevel>);
my $label = Gtk3::Label->new(q<Hello>);
my $provider = Gtk3::CssProvider->new();
$provider->load_from_data ($str, length($str));
my $style = $label->get_style_context();
$style->add_provider($provider, 600);
$window->add_events(q<GDK_SCROLL_MASK>);
$window->signal_connect(delete_event => sub{Gtk3->main_quit; FALSE});
$window->signal_connect(scroll_event => \&getWheel, [$style, $provider]);
$window->set_default_size(500, 300);
$window->add($label);
$window->show_all();
Gtk3->main;
Is there another way to modify the font-size of a running Gtk3 app?
You can also use pango_font_description_set_absolute_size(). For example:
use feature qw(say state);
use strict;
use warnings;
use constant MAX_FONT_SIZE => 200;
use constant MIN_FONT_SIZE => 12;
use Glib qw(TRUE FALSE);
use Gtk3 qw(init);
use Pango;
{
my $window = Gtk3::Window->new(q<toplevel>);
my $label = Gtk3::Label->new(q<Hello>);
set_label_font_size( $label, MIN_FONT_SIZE );
$window->add_events(q<GDK_SCROLL_MASK>);
$window->signal_connect(delete_event => sub{Gtk3->main_quit; FALSE});
$window->signal_connect(scroll_event => sub { get_wheel( $label, #_ ) } );
$window->set_default_size(500, 300);
$window->add($label);
$window->show_all();
Gtk3->main;
}
sub set_label_font_size {
my ( $label, $size ) = #_;
my $context = $label->get_pango_context();
my $font_description = $context->get_font_description();
$font_description->set_absolute_size($size * Pango::SCALE);
$context->set_font_description($font_description);
# A bug or am I missing somthing?? But for now I had to modify the label text in order
# for the fontsize to show up.
$label->set_text( $label->get_text() );
}
sub get_wheel {
my ($label, $widget, $event ) = #_;
my ($ctrl, $mod) = #{$event->state};
state $font_size = MIN_FONT_SIZE;
if ($ctrl eq q<control-mask> && $mod eq q<mod2-mask>) {
if ($event->direction eq q<up>) {
if ($font_size < MAX_FONT_SIZE) {
$font_size += 4;
}
}
elsif ($event->direction eq q<down>){
if ($font_size > MIN_FONT_SIZE) {
$font_size -= 4;
}
}
else {
return FALSE;
}
set_label_font_size( $label, $font_size );
}
return FALSE;
}

How can I speed up this nested foreach loop in Perl?

I have a Perl script that compares two sets of data loaded into two arrays, and I'm trying to make the comparison more efficient. Currently the code is as follows:
foreach(#{FILE_DATA}) {
if((++$file_current_linenum % 200) == 0) {
$progress = int($file_current_linenum / $file_total_lines * 10000) / 100;
logg("Processed $file_current_linenum file rows, $progress%, $mismatches mismatches.");
}
$file_current_line = $_;
$match_found = 0;
foreach(#{DB_DATA}) {
$db_current_line = $_;
if($file_current_line->{"channel"} == $db_current_line->{"channel"} ) {
if ($file_current_line->{"checksum"} == $db_current_line->{"checksum"} &&
$file_current_line->{"time"} > ($db_current_line->{"date_part"} - $TIME_MATCH_TOLERANCE) &&
$file_current_line->{"time"} < ($db_current_line->{"date_part"} + $TIME_MATCH_TOLERANCE) ){
$match_found = 1;
last; # break;
}
}
}
if($match_found != 1) {
push(#results, $file_current_line);
$mismatches++;
}
}
My first thought would be to remove matches from both arrays to reduce the pool size, would that affect the iterators position?
Both sets of data can have up to a couple of million elements and the comparison can take a few hours to complete.
Your solution is O(DB * FILE).
The following is O(DB + FILE) if and only if there never more than a few lines with the same channel and checksum:
my %DB_DATA;
for my $db_line (#DB_DATA) {
push #{ $DB_DATA{ $db_line->{channel} }{ $db_line->{checksum} } }, $db_line;
}
for my $file_line_idx (0..$#FILE_DATA) {
my $file_line = $FILE_DATA[$file_line_idx];
my $found = 0;
if (my $r1 = $DB_DATA{ $file_line->{channel} } ) {
if (my $r2 = $r1->{ $file_line->{checksum} } ) {
my $file_time = $file_line->{time};
for my $db_line (#$r2) {
my $db_time = $db_line->{date_part};
if (abs($file_time - $db_time) < $TIME_MATCH_TOLERANCE) {
$found = 1;
last;
}
}
}
}
push #mismatches, $file_line if !$found;
if ((($file_line_idx+1) % 200) == 0) {
logg(sprintf("Processed %d file rows, %d%, %d mismatches.",
$file_line_idx+1,
int(($file_line_idx+1)/#FILE_DATA) * 100,
0+#mismatches,
));
}
}
The following is O(DB + FILE) even if there are many lines with the same channel and checksum, but uses a lot of memory if $TIME_MATCH_TOLERANCE is big:
my %DB_DATA;
for my $db_line (#DB_DATA) {
for my $db_time (
$db_line->{date_part} - $TIME_MATCH_TOLERANCE + 1
..
$db_line->{date_part} + $TIME_MATCH_TOLERANCE - 1
) {
++$DB_DATA{ $db_line->{channel} }{ $db_line->{checksum} }{$db_time};
}
}
for my $file_line_idx (0..$#FILE_DATA) {
my $file_line = $FILE_DATA[$file_line_idx];
my $found = 0;
if (my $r1 = $DB_DATA{ $file_line->{channel} } ) {
if (my $r2 = $r1->{ $file_line->{checksum} } ) {
if ($r2->{ $file_line->{time} } {
$found = 1;
last;
}
}
}
push #mismatches, $file_line if !$found;
if ((($file_line_idx+1) % 200) == 0) {
logg(sprintf("Processed %d file rows, %d%, %d mismatches.",
$file_line_idx+1,
int(($file_line_idx+1)/#FILE_DATA) * 100,
0+#mismatches,
));
}
}
Note: Assumes the timestamps are integers. If they're not, convert them to integers before using them as keys.
The following is O((DB + FILE) log DB) [ which is very close to O(DB + FILE) ] even if there are many lines with the same channel and checksum, and uses minimal memory:
sub binsearch(&\#) {
my ($compare, $array) = #_;
my $i = 0;
my $j = $#$array;
return 0 if $j == -1;
while (1) {
my $k = int(($i+$j)/2);
for ($array->[$k]) {
my $cmp = $compare->()
or return 1;
if ($cmp < 0) {
$j = $k-1;
return 0 if $i > $j;
} else {
$i = $k+1;
return 0 if $i > $j;
}
}
}
}
my %DB_DATA;
for my $db_line (#DB_DATA) {
push #{ $DB_DATA{ $db_line->{channel} }{ $db_line->{checksum} } }, $db_line;
}
for my $r1 (values(%DB_DATA)) {
for my $r2 (values(%$r1)) {
#$r2 = sort { $a->{date_part} <=> $b->{date_part} } #$r2;
}
}
for my $file_line_idx (0..$#FILE_DATA) {
my $file_line = $FILE_DATA[$file_line_idx];
my $found = 0;
if (my $r1 = $DB_DATA{ $file_line->{channel} } ) {
if (my $r2 = $r1->{ $file_line->{checksum} } ) {
my $file_time = $file_line->{time};
my $min_db_time = $file_time - $TIME_MATCH_TOLERANCE;
my $max_db_time = $file_time + $TIME_MATCH_TOLERANCE;
if ( binsearch {
$_->{date_part} >= $max_db_time ? -1
: $_->{date_part} <= $min_db_time ? +1
: 0
} #$r2 ) {
$found = 1;
last;
}
}
}
push #mismatches, $file_line if !$found;
if ((($file_line_idx+1) % 200) == 0) {
logg(sprintf("Processed %d file rows, %d%, %d mismatches.",
$file_line_idx+1,
int(($file_line_idx+1)/#FILE_DATA) * 100,
0+#mismatches,
));
}
}
You could probably reduce the time significantly by pre-building a hash from DB_DATA, using the concatenation of the "channel" and "checksum" values as the key, and each value being a list of all of the DB_DATA entries with that channel and checksum. That way, for each FILE_DATA entry, you only need to check that list.
If there are a lot of entries with a given channel and checksum, you try to improve even more by sorting them by date_part, and then trying to binary search to find a valid entry.
If there are very few entries with a given channel and checksum, this should reduce your run time by a factor of a million or so, since it reduces the run time from O($#FILE_DATA * $#DB_DATA) to O($#FILE_DATA + $#DB_DATA).

Can't build perl class use autoload

class Gene
package Gene;
use strict;
use Carp;
use vars qw($AUTOLOAD);
my %_ok_gene_attr = (
"id" => "string",
"name" => "string",
"chrom" => "string", # chromosome or seq id
"txtStart" => "int", # 1-based
"txtEnd" => "int" # 1-based
);
sub new {
my ($class, %arg) = #_;
my $self = {};
$self->{_id} = $arg{id} || croak "no id";
$self->{_name} = $arg{name} || croak "no db";
$self->{_chrom} = $arg{chrom} || croak "no seq_id";
$self->{_strand} = $arg{strand} || -1;
$self->{_txStart} = $arg{txStart} || -1;
$self->{_txEnd} = $arg{txEnd} || -1;
$self->{_cdsStart} = $arg{cdsStart} || -1;
$self->{_cdsEnd} = $arg{cdsEnd} || -1;
$self->{_exonCount} = $arg{exonCount} || -1;
$self->{_exonStarts} = $arg{exonStarts} || -1;
$self->{_exonEnds} = $arg{exonEnds} || -1;
$self->{_score} = $arg{score} || -1;
$self->{_name2} = $arg{name2} || -1;
$self->{_cdsStartStat} = $arg{cdsStartStat} || -1;
$self->{_cdsEndStat} = $arg{cdsEndStat} || -1;
$self->{_exonFrames} = $arg{exonFrames} || -1;
bless($self, $class);
}
sub AUTOLOAD {
my ($self, $newvalue) = #_;
my ($operation, $attribute) = ($AUTOLOAD =~ /(get)(_\w+)$/);
unless ($operation && $attribute) {
croak "Method name $AUTOLOAD is not in the recognized form get_attribute\n";
}
unless (defined $_ok_gene_attr{$attribute}) {
croak "No such attribute '$attribute' exists in the class ", ref($self);
}
if ($operation eq 'get') {
*{$AUTOLOAD} = sub { shift->{$attribute} };
} elsif($operation eq 'set') {
*{$AUTOLOAD} = sub { shift->{$attribute} = shift };
$self->{$attribute} = $newvalue;
}
return $self->{$attribute};
}
sub DESTROY {
my($self) = #_;
$self->_decr_count( );
}
I use this class in
open my $in, '<', q/C:\Users\Jesse\Desktop\refGene.txt/ or die "Cannot open file : $!";
while(<$in>) {
chomp $_;
my #temp= split(/\t/, $_);
my $i=0;
my $temp1= Gene->new("id" => $temp[0],"name"=>$temp[1],"chrom"=>$temp[2], "strand"=>$temp[3],"txStart"=>$temp[4], "txEnd"=>$temp[5],"cdsStart"=>$temp[6],"cdsEnd"=>$temp[7],"exonCount"=>$temp[8],"exonStarts"=>$temp[9],"exonEnds"=>$temp[10],"score"=>$temp[11],"name2"=>$temp[12],"cdsStartStat"=>$temp[13],"cdsEndStat"=>$temp[14],"exonFrames"=>$temp[15]);
}
is has a error
(in cleanup) Method name Gene::_decr_count is not in the recognized form get_attribute
It also seems the autoload function doesn't work when i use $temp1->set_id("1234")?
Try this some kind of fixed version of Gene.pm:
package Gene;
use strict;
use Carp;
use vars qw($AUTOLOAD);
use Data::Dumper;
my %_ok_gene_attr = (
"_id" => "string",
"_name" => "string",
"_chrom" => "string", # chromosome or seq id
"_txtStart" => "int", # 1-based
"_txtEnd" => "int" # 1-based
);
sub new {
my ($class, %arg) = #_;
my $self = {};
$self->{_id} = $arg{id} || croak "no id";
$self->{_name} = $arg{name} || croak "no db";
$self->{_chrom} = $arg{chrom} || croak "no seq_id";
$self->{_strand} = $arg{strand} || -1;
$self->{_txStart} = $arg{txStart} || -1;
$self->{_txEnd} = $arg{txEnd} || -1;
$self->{_cdsStart} = $arg{cdsStart} || -1;
$self->{_cdsEnd} = $arg{cdsEnd} || -1;
$self->{_exonCount} = $arg{exonCount} || -1;
$self->{_exonStarts} = $arg{exonStarts} || -1;
$self->{_exonEnds} = $arg{exonEnds} || -1;
$self->{_score} = $arg{score} || -1;
$self->{_name2} = $arg{name2} || -1;
$self->{_cdsStartStat} = $arg{cdsStartStat} || -1;
$self->{_cdsEndStat} = $arg{cdsEndStat} || -1;
$self->{_exonFrames} = $arg{exonFrames} || -1;
bless($self, $class);
}
sub AUTOLOAD {
my ($self, $newvalue) = #_;
my ($operation, $attribute) = ($AUTOLOAD =~ /(get|set)(_\w+)$/);
unless ($operation && $attribute) {
croak "Method name $AUTOLOAD is not in the recognized form set_{attribute} or get_{attribute}\n";
}
unless (defined $_ok_gene_attr{$attribute}) {
croak "No such attribute '$attribute' exists in the class ", ref($self);
}
if ($operation eq 'get') {
no strict 'refs';
*{$AUTOLOAD} = sub { shift->{$attribute} };
} elsif($operation eq 'set') {
no strict 'refs';
*{$AUTOLOAD} = sub { shift->{$attribute} = shift };
$self->{$attribute} = $newvalue;
}
return $self->{$attribute};
}
sub DESTROY {
my($self) = #_;
$self->_decr_count( );
}
Tested with the following script:
#!/usr/bin/perl
use strict;
use warnings;
use Gene;
my $t1 = Gene->new(id=>"id", name=>"name", chrom=>"chrom");
$t1->set_id("1234");
print $t1->get_id(), "\n";
Beside using Perl's builtin OO system, you may also want to take a look of some other OO system, such as Moose. See perlootut for further details.

Safe way to establish the initial state again.

Is there a possibility of calling the function main without the function _end_win being called?
#!/usr/bin/env perl
use warnings;
use strict;
use 5.10.0;
use Term::ReadKey;
use constant {
NEXT_getch => -1,
CONTROL_C => 0x03,
CONTROL_D => 0x04,
KEY_ENTER => 0x0d,
KEY_RIGHT => 0x1b5b43,
KEY_LEFT => 0x1b5b44,
};
say main();
sub main {
my $arg = {};
$arg->{handle_out} = *STDOUT;
_init_scr( $arg );
while ( 1 ) {
my $c = _getch( $arg );
if ( ! defined $c ) {
_end_win( $arg );
warn "EOT";
return;
}
next if $c == NEXT_getch;
given ( $c ) {
when ( $c >= 97 && $c <= 122 ) {
print chr $c;
$arg->{string} .= chr $c;
}
when ( $c == KEY_RIGHT ) {
print '>';
$arg->{string} .= '>';
}
when ( $c == KEY_LEFT ) {
print '<';
$arg->{string} .= '<';
}
when ( $c == CONTROL_D ) {
_end_win( $arg );
return;
}
when ( $c == CONTROL_C ) {
_end_win( $arg );
print STDERR "^C";
kill( 'INT', $$ );
return;
}
when ( $c == KEY_ENTER ) {
_end_win( $arg );
return $arg->{string};
}
}
}
}
sub _init_scr {
my ( $arg ) = #_;
$arg->{old_handle} = select( $arg->{handle_out} );
$arg->{backup_flush} = $|;
$| = 1;
Term::ReadKey::ReadMode 'ultra-raw';
}
sub _end_win {
my ( $arg ) = #_;
print "\n\r";
Term::ReadKey::ReadMode 'restore';
$| = $arg->{backup_flush};
select( $arg->{old_handle} );
}
sub _getch {
my ( $arg ) = #_;
my $c1 = ReadKey 0;
return if ! defined $c1;
if ( $c1 eq "\e" ) {
my $c2 = ReadKey 0.10;
if ( ! defined $c2 ) { return NEXT_getch; }
elsif ( $c2 eq 'C' ) { return KEY_RIGHT; }
elsif ( $c2 eq 'D' ) { return KEY_LEFT; }
elsif ( $c2 eq '[' ) {
my $c3 = ReadKey 0;
if ( $c3 eq 'C' ) { return KEY_RIGHT; }
elsif ( $c3 eq 'D' ) { return KEY_LEFT; }
else {
return NEXT_getch;
}
}
else {
return NEXT_getch;
}
}
else {
return ord $c1;
}
}
To ensure that the terminal is reset when your program exits, put the reset code into an END block. For example, you could replace your _end_win sub with:
END {
print "\n\r";
Term::ReadKey::ReadMode 'restore';
}
(I removed the lines resetting $| and the selected output filehandle since the process is exiting anyhow, so they're about to become irrelevant.)
An END block will always run when the program terminates in a "normal" way, such as calling exit or die or hitting the end of the executable code. It does not fire when the process terminates due to receiving a signal; it looks like you're handling the ctrl-C character directly, but you may want to consider adding a %SIG{INT} handler as well, in case someone sends you a kill -2.