Last question--
I'm using file locking (multiple builds going on at once, so I don't want collisions)
If I put
Code:
flock ($newlicense_fh, 2)
in this block
Code:
open my $newlicense_fh, '>', $newFile or die "failed to open '$newFile' <$!>";
flock ($newlicense_fh, 2)
foreach my $hostname ( keys %licenses ) {
foreach my $license ( @{ $licenses{ $hostname } } ) {
print {$newlicense_fh} "$hostname $license\n";
}
}
close $newlicense_fh;
}
}
I get
Code:
"my" variable $hostname masks earlier declaration in same statement at k:\Packages\Packages\MirrorFolder4.1\autoAssign.pl line 50.
syntax error at k:\Packages\Packages\MirrorFolder4.1\autoAssign.pl line 49, near "$hostname ("
syntax error at k:\Packages\Packages\MirrorFolder4.1\autoAssign.pl line 50, near "} ) "
Global symbol "$newlicense_fh" requires explicit package name at k:\Packages\Packages\MirrorFolder4.1\autoAssign.pl line 51.
Execution of k:\Packages\Packages\MirrorFolder4.1\autoAssign.pl aborted due to compilation errors.
If I remove the lock, the script works.
I'm using a shared lock when the files is read, and an exclusive lock when the new file is written.
From what I saw about locking, I (think) I did it right, but apparently not.
Is there a better way? Should I use lockf or something else?
Thanks!
Full code:
Code:
#!/usr/bin/perl
use warnings;
use strict;
use File::Copy;
use Data::Dumper;
my $path = 'k:/Packages/Packages/MirrorFolder4.1';
my $file = "$path/testlicense.txt";
my $backup = "$path/testlicense.bak";
my $newFile = "$path/new-license.txt";
my $strSearchFor = "unassigned";
my $setCount = 0;
my %licenses;
open my $license_fh, '<', $file or die "failed to open '$file' $!";
flock ($license_fh, 1);
#read file in
LICENSE:
while ( my $line = <$license_fh> ) {
chomp $line;
next LICENSE if $line =~ /^\s*$/;
my ($hostname, $license) = split / /, $line, 2;
unless ($hostname and $license) {
print Dumper $line;
next LICENSE;
}
push @{ $licenses{$hostname} }, $license;
}
close $license_fh;
move($file, $backup) or die "copy failed: $!"; #make a backup of the license file
#look for the word 'unassigned' and replace the first one with the computer name
while($setCount == 0){
print "while loop...\n";
print "Found so far- " . $setCount . "\n";
if ( exists $licenses{$strSearchFor} ) {
print "found unassigned license key...\n" ;
$licenses{ $ENV{'COMPUTERNAME'} } = [shift @{ $licenses{ 'unassigned' } }];
print "substitued current computer name...\n";
$setCount = 1;
print "Found so far- " . $setCount . "\n";
print "opening new license file for writing...\n";
open my $newlicense_fh, '>', $newFile or die "failed to open '$newFile' <$!>";
flock ($newlicense_fh, 2)
foreach my $hostname ( keys %licenses ) {
foreach my $license ( @{ $licenses{ $hostname } } ) {
print {$newlicense_fh} "$hostname $license\n";
}
}
close $newlicense_fh;
}
}