Regex 重构链式elsif(使用正则表达式)以在Perl中调度表。但是我的代码是如何工作的呢?
我有一个像这样的长链if-elsif块,其中我使用capture::Tiny捕获命令的输出,然后使用一系列正则表达式提取它Regex 重构链式elsif(使用正则表达式)以在Perl中调度表。但是我的代码是如何工作的呢?,regex,perl,Regex,Perl,我有一个像这样的长链if-elsif块,其中我使用capture::Tiny捕获命令的输出,然后使用一系列正则表达式提取它 sub capture_cpu_test { my ($cmd) = @_; print '--------------------', "\n"; print 'COMMAND is: ', "$cmd", "\n"; #capture an output of sysbench command my ( $stdout_to_f
sub capture_cpu_test {
my ($cmd) = @_;
print '--------------------', "\n";
print 'COMMAND is: ', "$cmd", "\n";
#capture an output of sysbench command
my ( $stdout_to_format, $stderr, $exit ) = capture {
system($cmd );
};
#split on newline to separately analyze later
my @output_lines = split( "\n", $stdout_to_format );
#set hash to collect param => param_value pairs
my %plotting_hash = ();
foreach my $line (@output_lines) {
if ( $line =~ m/\ANumber\s+of\s+threads:\s+(\d+)\z/xms ) {
$plotting_hash{num_threads} = $1;
}
#long list of elseif continues
elsif ( $line =~ m{\A\s+events\s+\(avg\/stddev\):\s+(.+?)\/(.+?)\z}xms ) {
$plotting_hash{events_avg} = $1;
$plotting_hash{events_stddev} = $2;
}
}
#returns ref to plotting_hash to combine upstream
my $hash_plot_ref = \%plotting_hash;
print 'Printing $hash_plot_ref inside capture_cpu_test: ', "\n";
print Dumper($hash_plot_ref);
return $hash_plot_ref;
}
我想让它更具可读性,所以我将此elsif块更改为使用网络上的答案调度表,没问题,它可以工作:
#set dispatch table with regex => sub {} pairs
my %plotting_hash = ();
my %dispatch_regex = (
qr/\ANumber\s+of\s+threads:\s+(\d+)\z/xms =>
sub { $plotting_hash{num_threads} = $1 },
#more entries here
qr{\A\s+events\s+\(avg\/stddev\):\s+(.+?)\/(.+?)\z}xms =>
sub { $plotting_hash{events_avg} = $1;
$plotting_hash{events_stddev} = $2; },
);
#populate the %plotting_hash by calling dispatch table (%dispatch_regex)
my $code_ref;
foreach my $line (@output_lines) {
foreach my $regex ( keys %dispatch_regex ) {
if ( $line =~ $regex ) {
$code_ref = $dispatch_regex{$regex};
$code_ref->();
last;
}
}
}
我得到这样的东西:
$hash_plot_ref = {
'num_threads' => '4',
'events_stddev' => '50.98',
'events_avg' => '2500.0000',
...
};
if ( $line =~ $regex ) {
如果成功,$1和$2等将具有成功匹配的值。顺便说一下,您知道
(something)
正则表达式引擎使用位来提供$1、$2等
我不知道你在没有花时间思考的情况下说的三分之一是什么意思,-你真的想要澄清吗?如果是,请发布一个新问题,或在此问题上添加更多信息,以便解决。1。谢谢你的澄清。使用全局$1和$2。。。看起来不安全。你知道如何使它更安全并保持调度表工作吗?2.不需要澄清,它只是一大块代码,这对手头的问题很好。