
use strict;
use warnings;

use Fcntl qw(:flock SEEK_SET); #constants needed for seek and flock

if (open(my $fd,"+<","inventory.dat")) { #open file for read/write
    my $available = <$fd>;	#the number in stock 
    chomp $available;	#get rid of the end of line characater
    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
            #since we want to update the file, lock it, 
            # re-read in case someone else already changed it.  
            # Re-check the value and update if there are still
            #  some to reduce
            flock($fd,LOCK_EX); #make sure we get exclusive use 
                                # of the file while we update it
            seek($fd,SEEK_SET,0); #prepare to re-read, incase 
                            # another user updated
            my $available = <$fd>; #the number now available
            if ($available-- > 0) { #there were still some
                seek($fd,SEEK_SET,0); #so we can overwrite
                print $fd "$available\n"; #update the file
            }
            else {
                print "Sadly someone beat you to it!\n";
            }
        flock($fd,LOCK_UN); #unlock the lock
        } 
    }
} #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";
}
