#!/usr/bin/perl -w # safeinc: safely read and increment a number stored in a file. my $rcsid = '$Id: doit,v 1.1 2006/02/15 19:51:25 vogelke Exp $'; use Getopt::Long; use Pod::Usage; use File::Basename; use Fcntl qw(:DEFAULT :flock); use strict; my $myname = basename($0); $myname =~ s/\.\w*$//; # strip any extension my %options; my @getopt_args = ( 'f=s', # output format 'h|?', # print usage 'm', # print manpage 'v', # print version ); Getopt::Long::config("noignorecase", "bundling"); usage() unless GetOptions(\%options, @getopt_args); manpage() if $options{'m'}; version() if $options{'v'}; usage() if $options{'h'}; usage() unless $options{'f'}; # # Real work starts here. # my ($ofh, $num); my $numfile = $options{'f'}; sysopen(FH, "$numfile", O_RDWR | O_CREAT) or die "can't open $numfile: $!"; $ofh = select(FH); $| = 1; select($ofh); # autoflush FH flock(FH, LOCK_EX) or die "can't write-lock $numfile: $!"; $num = || 0; seek(FH, 0, 0) or die "can't rewind $numfile : $!"; print FH $num + 1, "\n" or die "can't write $numfile: $!"; truncate(FH, tell(FH)) or die "can't truncate $numfile: $!"; close(FH) or die "can't close $numfile: $!"; exit(0); #--------------------------------------------------------------------- # Print a usage message from the comment header and exit. sub usage { my ($emsg) = @_; require Pod::Usage; import Pod::Usage qw(pod2usage); warn "$emsg\n" if defined $emsg; pod2usage(-verbose => 1); } sub manpage { require Pod::Usage; import Pod::Usage qw(pod2usage); pod2usage(-exitstatus => 0, -verbose => 2); } #--------------------------------------------------------------------- # Print the current version and exit. sub version { $_ = $rcsid; s/,v / /; @_ = split; print "$myname v$_[2] $_[3] $_[4]\n"; exit(0); } #--------------------------------------------------------------------- __END__ =head1 NAME safeinc - safely read and increment a number stored in a file. =head1 SYNOPSIS safeinc [-hmv] -f file =head1 OPTIONS =over 4 =item B<-f> file Specify the file holding the number to increment - required. =item B<-h> Print a brief help message and exit. =item B<-m> Print the manual page and exit. =item B<-v> Prints the version and exits. =back =head1 DESCRIPTION B will read the given input file(s) and safely increment the number within. =head1 AUTHOR Based on an example found in http://www.mkssoftware.com/docs/man5/perlopentut.5.asp =cut