package JSONFile; use strict; use warnings; use JSON; use IO::File; use Fcntl qw(:flock); use Carp; sub new{ my $class = shift; my %cfg = ( lock => 0, file => '', mode => O_RDONLY, @_); eval{ my $fh = IO::File->new; $fh->open($cfg{file}, $cfg{mode}) or croak "Error open file '$cfg{file}', $!"; if($cfg{lock}){ flock($fh, LOCK_EX)|| carp "Problem mit LOCK_EX, $!" } bless{ FH => $fh, CFG => \%cfg, JSN => JSON->new }, $class; } } sub freeze{ my $self = shift; my $ref = shift; $self->{FH}->truncate(0); $self->{FH}->seek(0,0); $self->{FH}->print( $self->{JSN}->encode($ref) ); } sub thaw{ my $self = shift; $self->{FH}->seek(0,0); read($self->{FH}, my $raw, -s $self->{FH}); $self->{JSN}->decode($raw); } 1;######################################################################### __END__ use Data::Dumper; my $f = JSONFile->new( file => "d:/tmp/xdata.jn", mode => O_CREAT|O_RDWR, lock => 1 ) or die $@; $f->freeze(['รค']); my $r = $f->thaw; print "@$r";