简体   繁体   English

在Perl中处理文件的某些行

[英]Manipulating certain lines of a file in Perl

This is basically a question regarding file manipulation. 这基本上是关于文件操作的问题。 I'm working on a Perl script that will run as a cron job that sends an email when certain values shows up on a web page, but does so only once until the value resets (it's a page of reports containing audits that show an alert when a report requires attention). 我正在研究一个Perl脚本,它将作为cron作业运行,当某些值显示在网页上时发送一封电子邮件,但是仅执行一次,直到该值重置(这是包含审计并显示警报的报告页面当报告需要引起注意时)。 I've figured out how to parse the page for alerts, I know how to send emails via Perl, I'm just having a hard time figuring out the logic for WHEN to send the email. 我已经找到了如何解析页面警报的方法,我知道如何通过Perl发送电子邮件,但是我很难确定何时发送电子邮件的逻辑。 I gather that a separate file (alerts.txt) will need to be created to store the reports that had an alert during the previous execution of the script. 我收集到,需要创建一个单独的文件(alerts.txt)来存储在脚本的先前执行过程中具有警报的报告。 In that case you have 4 scenarios to handle in the script. 在这种情况下,脚本中有4种情况需要处理。 1) The report has an alert and isn't in alerts.txt (needs to be added). 1)该报告具有警报,不在Alerts.txt中(需要添加)。 2) The report doesn't have an alert but is in alerts.txt from a previous execution of the script (needs to be removed). 2)该报告没有警报,但位于脚本先前执行的alert.txt中(需要删除)。 3) The report doesn't have an alert and isn't in alerts.txt (do nothing). 3)该报告没有警报,也不在Alerts.txt中(不执行任何操作)。 4) The report has an alert and is already in alerts.txt (do nothing). 4)该报告具有警报,并且已经在Alerts.txt中(不执行任何操作)。

Is this the best way to go about this? 这是解决此问题的最佳方法吗? If so, what's the best way to implement scenarios #1 and #2 above? 如果是这样,实现上述方案#1和#2的最佳方法是什么?

I am assuming you've chosen not to use a database - which is valid in some situations but you may change your mind as your application grows. 我假设您选择不使用数据库-在某些情况下这是有效的,但是随着应用程序的增长,您可能会改变主意。

The simplest method, is to use the Storable modules which comes built in with perl. 最简单的方法是使用perl内置的Storable模块。 Note, this produces non human readable formats but can store quite complex data structures; 注意,这会产生非人类可读的格式,但可以存储非常复杂的数据结构;

#!/usr/bin/env perl
use Storable;

# Create some alerts data, and store it in a data file
my $alerts = {};
$alerts->{report_01} = 'alert';
$alerts->{report_02} = 'ok';
store $alerts, 'alerts.data';

# Read it back
my $prev_alerts = retrieve('alerts.data');
foreach my $key (keys %$prev_alerts) {
 print "$key=$prev_alerts->{$key}\n";
}

If you desire a human readable format there are various options that support file based storage; 如果您希望使用人类可读的格式,则可以使用多种选项来支持基于文件的存储。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM