File-SharedVar

 view release on metacpan or  search on metacpan

lib/File/SharedVar.pm  view on Meta::CPAN

    die $self->{file},": No such file";
  }
  $self->{lock}=$self->{file}.".lock" if($args{mutex} && $args{mutex} eq 'lock');
  return $self;
}



=head2 read

  my $value = $shared_var->read($key);

Reads the value associated with the given key from the shared variable file.

=over 4

=item *

C<$key>: The key whose value you want to read.

=back

Returns the value associated with the key, or C<undef> if the key does not exist.

=cut

sub read {
  my ($self, $key) = @_;
  my($data)= _load_from_file($self);
  return $data->{$key};
}



=head2 update

  my $new_value = $shared_var->update($key, $value, $increment);

Updates the value associated with the given key in the shared variable file.

=over 4

=item *

C<$key>: The key to update.

=item *

C<$value>: The value to set or increment by.

=item *

C<$increment>: If true (non-zero), increments the existing value by C<$value>; otherwise, sets the key to C<$value>.

=back

Returns the previous value associated with the key, from before the update.

=cut

sub update {
  my($self, $key, $val, $inc) = @_;
  my($data)= _load_from_file($self,1);
  my $ret = $data->{$key};

  # Update the value for the key
  if($inc) {
    $data->{$key} = ($data->{$key} // 0) + $val;
  } else {
    $data->{$key} = $val;
  }
  _save_to_file($self,$data);

  return $ret;
}



sub _load_from_file {
  my($self,$staylocked)=@_;

  if($self->{lock}) {
    sysopen($self->{lfh}, $self->{lock}, O_EXCL | O_CREAT ) or die "Cannot open $self->{lock}: $!";
    die "incomplete";
  }

  open $self->{fh}, '+<', $self->{file} or die "$$ Cannot open $self->{file}: $!";
  #sysopen($self->{fh}, $self->{file}, $O_RDWR) or die "Cannot open $self->{file}: $!";

  my $data = {};

  &dbg( "$$ pre-lock" );
  flock($self->{fh}, $LOCK_EX) or die "$$ Cannot lock: $!";
  my $json_text = undef; do { local $/; $json_text=readline($self->{fh}) };
  #my $json_text = undef; do { local $/; my $fh=$self->{fh}; <$fh> };
  &dbg( "$$ post-lock d=$json_text" );
  #my $json_text; sysread($self->{fh},$json_text,65535); 
  $data = decode_json($json_text) if $json_text;
  unless($staylocked){  # LOCK_UN (unlock)
    flock($self->{fh}, $LOCK_UN) or die "$$ Cannot unlock: $!";
    $self->{fh}->close; $self->{fh}=undef;
    if($self->{lock}) {
      die "incomplete";
    }
  }
  return($data);
} # _load_from_file


sub _save_to_file {
  my ($self,$data) = @_;
  seek($self->{fh}, 0, 0) or die "$$ Cannot seek: $!";
  truncate($self->{fh}, 0) or die "$$ Cannot truncate $self->{file} file: $!";
  print { $self->{fh} } encode_json($data);
  #syswrite($self->{fh},encode_json($data));
  flock($self->{fh}, $LOCK_UN) or die "$$ Cannot unlock: $!";  # LOCK_UN (unlock)
  $self->{fh}->close; $self->{fh}=undef; 
  if($self->{lock}) {
    die "incomplete";
  }
} # _save_to_file



( run in 0.337 second using v1.01-cache-2.11-cpan-63c85eba8c4 )