Como posso verificar o tamanho do arquivo e adicionar esse resultado em uma planilha do Excel em Perl?
Pergunta
Atualmente estou monitorando um arquivo específico com uma linha simples de shell:
filesize=$(ls -lah somefile | awk '{print $5}')
Estou ciente de que Perl tem alguns módulos interessantes para lidar com arquivos Excel, então a idéia é, digamos, executar essa verificação diariamente, talvez com cron, e escrever o resultado em uma planilha para uso estatístico posterior.
Solução
Você pode verificar o tamanho do arquivo usando o operador -s.
use strict; use warnings; use File::Slurp qw(read_file write_file); use Spreadsheet::ParseExcel; use Spreadsheet::ParseExcel::SaveParser; use Spreadsheet::WriteExcel; my $file = 'path_to_file'; my $size_file = 'path_to_file_keeping_the_size'; my $excel_file = 'path_to_excel_file.xls'; my $current_size = -s $file; my $old_size = 0; if (-e $size_file) { $old_size = read_file($size_file); } if ($old_size new; my $excel = $parser->Parse($excel_file); my $row = 1; $row++ while $excel->{Worksheet}[0]->{Cells}[$row][0]; $excel->AddCell(0, $row, 0, scalar(localtime)); $excel->AddCell(0, $row, 1, $current_size); my $workbook = $excel->SaveAs($excel_file); $workbook->close; } else { my $workbook = Spreadsheet::WriteExcel->new($excel_file); my $worksheet = $workbook->add_worksheet(); $worksheet->write(0, 0, 'Date'); $worksheet->write(0, 1, 'Size'); $worksheet->write(1, 0, scalar(localtime)); $worksheet->write(1, 1, $current_size); $workbook->close; } } write_file($size_file, $current_size);
Uma maneira simples de escrever arquivos Excel seria usarPlanilha::Escrever.mas se você precisar atualizar um arquivo Excel existente, você deve dar uma olhadaPlanilha::ParseExcel.
Outras dicas
Você pode usar o -s
operador para obter o tamanho de um arquivo e o Planilha::ParseExcel e Planilha::WriteExcel módulos para produzir uma planilha atualizada com as informações. Planilha::ParseExcel::SaveParser permite combinar facilmente os dois, caso queira atualizar um arquivo existente com novas informações.Se você estiver no Windows, talvez queira automatizar o próprio Excel, provavelmente com a ajuda de Win32::OLE.
Você também pode evitar o incômodo de escrever arquivos no formato .xls e usar um formato mais genérico (mas suficientemente compatível com Excel), como CSV:
#!/bin/bash
date=`date +%Y/%m/%d:%H:%M:%S`
size=$(ls -lah somefile | awk '{print $5}')
echo "$date,$size"
Então, no seu crontab:
0 0 * * * /path/to/script.sh >/data/sizelog.csv
Em seguida, você importa esse arquivo .csv para o Excel como qualquer outra planilha.
Perl também tem o muito bom (e muito rápido) Texto::CSV_XS que permite criar facilmente arquivos CSV compatíveis com Excel, o que pode ser uma solução melhor do que criar arquivos XLS adequados.
Por exemplo (comentado demais para valor instrucional):
#!/usr/bin/perl
package main;
use strict; use warnings; # always!
use Text::CSV_XS;
use IO::File;
# set up the CSV file
my $csv = Text::CSV_XS->new( {eol=>"\r\n"} );
my $io = IO::File->new( 'report.csv', '>')
or die "Cannot create report.csv: $!\n";
# for each file specified on command line
for my $file (@ARGV) {
unless ( -f $file ) {
# file doesn't exist
warn "$file doesn't exist, skipping\n";
next;
}
# get its size
my $size = -s $file;
# write the filename and size to a row in CSV
$csv->print( $io, [ $file, $size ] );
}
$io->close; # make sure CSV file is flushed and closed
O módulo que você deve usar é Planilha::WriteExcel.