I would like to prevent multiple invocation of a Perl script based on a variable or command-line arguments. Extending this answer:
#!/usr/bin/env perl
use strict;
use warnings;
use Getopt::Long;
my ( $foo, $bar );
GetOptions (
"foo" => \$foo,
"bar" => \$bar,
) || die "usage: $0 [ -foo | -bar ]\n";
use Fcntl ':flock';
flock(DATA, LOCK_EX|LOCK_NB) or die "There can be only one! [$0]";
say STDOUT (($foo?"foo":$bar?"bar":"nobody")." sleeps");
sleep(2);
# mandatory, flocking depends on DATA file handle
__DATA__
How can I lock app.pl -foo
and app.pl -bar
independently?