#!/usr/bin/perl
#
# Read a specified amount of kibibytes from STDIN
# and print them to STDOUT. Once the set limit
# is reached, exit with exit code 1, if EOF is
# encountered, exit with code 0
#
# by Stefan Tomanek <stefan.tomanek@wertarbyte.de>
# http://wertarbyte.de/

use strict;
use warnings;
use bytes;

my $limit = $ARGV[0] * 1024;
my $size = 1024;
$| = 1;
my $data;
while( my $read_bytes = sysread(STDIN, $data, $size) ) {
    print $data;
    $limit -= $read_bytes;
    # Shrink the amount of data to be read to the limit
    $size = $limit if $limit < $size;
    # print STDERR "limit is $limit\n";
    exit 1 if $limit == 0;
}
exit 0;
