http://qs1969.pair.com?node_id=1172349


in reply to Limit Socket (throttle) to send specific ammount of packets every second

G'day Lucas,

Welcome to the Monastery.

Firstly, you can put long tracts of code within <readmore>...</readmore> or <spoiler>...</spoiler> tags: see "Writeup Formatting Tips" for details.

Unfortunately, without seeing the surrounding code, it's difficult to tell what additional code will be appropriate. There may well be better solutions!

The following demonstrates how you might achieve what you ask using an alarm (actually, it uses Time::HiRes's ualarm for finer granularity).

#!/usr/bin/env perl -l use strict; use warnings; use Time::HiRes qw{ualarm time}; my $timeout = 1_000_000; #microseconds my $limit = 3; my @packets = (0 .. 11); print time; { my $local_limit = $limit; local $SIG{ALRM} = sub { print time; $local_limit = $limit; ualarm $timeout; }; ualarm $timeout; while (1) { next unless $local_limit-- > 0; last unless @packets; my $line = shift @packets; ualarm 1 if $line == 6; print $line; } }

Here's a sample run:

1474530606.74812 0 1 2 1474530607.75322 3 4 5 1474530608.75744 6 1474530608.75752 7 8 9 1474530609.75927 10 11

Notes:

See also: "perlipc -- Perl interprocess communication".

Update: s/last unless eof/last if eof/

— Ken