use strict;
use warnings;

use Fcntl qw(:flock SEEK_SET); #allocate the constants that we need
    # for locking and unlocking and seeking within the file.  The
    # OS expects numeric values for these but this provides us
    # more convenient, human readable constants assigned those values


if (open(my $fd,"+<","inventory.dat")) { #open file for read/write
    flock($fd,LOCK_EX);	#set an Exclusive flock on the file, if
                        # someone else has it flocked then we
                        # block/pause here until they release it
    my $available = <$fd>; #the number in stock - and BTW, we have 
                        # the flock set or we could not be here
    chomp $available;	#get rid of the end of line character
    print "There are $available widgets in stock\n";
    if ($available > 0) {
        print "shall I reduce the number? ";
        my $y = <STDIN>; #keyboard input
        if ($y =~ /^y/i) { #if input starts with y or Y
            $available--; #reducing
            seek($fd,SEEK_SET,0); #seek() sets the file pointer
                # in the file so that we do not just print
                # right after where we read, which is where
                # the pointer was left by the <$fd> above.
                # SEEK_SET instructs the OS to set the pointer
                # to the position that follows, here 0, being
                # the start of file.  seek() is very similar
                # to Python's seek
            print $fd "$available\n"; #update the file
        }
    }
} #as we fall out of the block $fd goes out of scope and so the file 
  # is closed and the flock released
else {
    die "can't open the inventory file";
}
