Subversion Repositories havirt

Rev

Rev 4 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

#!/usr/bin/env perl

# Common library for havirt. Basically, just a place to put things which may be used by any
# part of havirt.

# v0.0.1 20240602 RWR
# Initial setup

package havirt;


our $VERSION = '0.01';
use warnings;
use strict;  

use Data::Dumper qw(Dumper); # Import the Dumper() subroutine

use Exporter;

our @ISA = qw( Exporter );
our @EXPORT = qw( 
                  &readDB &writeDB
                  &report_tsv &report_screen
                );



sub readDB {
   my ($filename) = @_;
   my $yaml = YAML::Tiny->new( {} );
   if ( -f $filename ) {
      $yaml = YAML::Tiny->read( $filename );
   }
   return $yaml->[0];
}

sub writeDB {
   my ($filename,$data) = @_;
   my $yaml = YAML::Tiny->new( $data );
   $yaml->write( $filename );
}

sub report_tsv {
   my ( $header, $data ) = @_;
   my @output;
   push @output, join( "\t", @$header );
   for( my $line = 0; $line < @$data; $line++ ) {
      push @output, join( "\t", @{$data->[$line]} );
   } # for
   return join( "\n", @output ) . "\n";
}

sub report_screen {
   my ( $header, $data ) = @_;
   my @output;
   my @widths;
   my $column;
   my $row;
   # First, initialize by using the length of the headers
   for ( $column = 0; $column < @$header; $column++ ) {
      @widths[$column] = length( $header->[$column] );
   }
   # now, go through all data in each row, for each column, and increment the width if it is larger
   for ( $row = 0; $row < @$data; $row++ ) {
      for ( $column = 0; $column < @$header; $column++ ) {
         $widths[$column] = length( $data->[$row][$column] ) 
            if length( $data->[$row][$column] ) > $widths[$column];
      } # for column
   } # for row
   # actually do the print now
   my @format;
   for ( $column = 0; $column < @widths; $column++ ) {
      push ( @format, '%' . $widths[$column] . 's' );
   }
   my $format = join( ' ', @format ) . "\n";
   my $output = sprintf( $format, @$header );
   for ( $row = 0; $row < @$data; $row++ ) {
      $output .= sprintf( $format, @{$data->[$row]} );
   } # for row
   return $output;
}