Re: Streamlined application/script development [Re: coding an Application in perl]

Jean-Louis Martineau <[email protected]> Tue, 12 Sep 2017 07:58:57 -0400
Newsgroups gmane.comp.archivers.amanda.devel
Message-ID <[email protected]>
For read_local_state and write_local_state,

Why do not simply use Data::Dumper to write the data and eval to parse it?
It is what we do for the changer state file and it works well.
No need to format the output or parse it, everything is done by perl.

Not tested:

sub read_local_state {
     my ( $self ) = @_;
     my $state;
     my ( $dirpart, $filepart ) = $self->local_state_path();
     my $statefile = File::Spec->catfile($dirpart, $filepart);
     my $ret = open my $fh, '<', $statefile;
     if ( ! $ret ) {
         my %empty = ( 'maxlevel' => 0 );
         return \%empty;
     }
     my $slurped;
     {
         local $/;
         $slurped = <$fh>;
     }
     close $fh;
     if ($slurped) {
         eval $slurped;  # set $state
         if ($@) {
             debug("error reading '$statefile': $@");
             $levhash = {};
         }
         if (!defined $state || ref($state) ne "hash") {
             debug("'$statefile' did not define \$state properly");
             $state={};
         }
      } else {
         $state={};
      }
      my $maxlevel = -1;
      foreach my $key (keys %$state) {
         $maxlevel = $key if $key > $maxlevel;
      }
      $state->{'maxlevel'} = 1 + $maxlevel;
      return $state;
}

sub write_local_state {
     my ( $self, $state ) = @_;
     my $dumper = Data::Dumper->new([ $state ], ["state"]);
     $dumper->Purity(1);
     my $state_string = $dumper->Dump;
     my ( $dirpart, $filepart ) = $self->local_state_path();
     make_path($dirpart);
Amanda::Util::safe_overwrite_file(File::Spec->catfile($dirpart, $filepart),
                                       $state_string);
}
This message is the property of CARBONITE, INC. and may contain confidential or privileged information.
If this message has been delivered to you by mistake, then do not copy or deliver this message to anyone.  Instead, destroy it and notify me by reply e-mail