我有一个脚本可以读取CAN总线信号并将其显示在屏幕上,但我需要添加信号计数器和频率。
所以我需要计算到目前为止这个$ id出现了多少次以及多少毫秒之前它被添加到哈希表中。
#!/usr/bin/perl -w
use strict;
open my $can_bus, "./receivetest |"
or die "Couldn't read from CAN bus: $!";
my %last_value;
while (<$can_bus>) {
if( /^(........:...) (........) (.*)$/ )
{
my ($something, $id, $payload) = ($1,$2,$3);
$last_value{ $id } = $payload;
system('clear'); #clear screen
#Print Table
for my $id (sort keys %last_value) {
print "$id\t $last_value{ $id }\n";
}
}
else {
warn "ignore unknown line: ";
warn $_;
}
}
到目前为止,这是我的代码。
答案 0 :(得分:1)
如果通过在$id
键后添加更多键来扩展哈希,则可以为一个$id
键存储不同的值。例如:
if (defined $last_value{ $id } ){
$last_value{ $id }{COUNT} += 1;
my $time_diff = $now_milli - $last_value{ $id }{TIME};
$last_value{ $id }{TIME} = $now_milli;
$last_value{ $id }{DIFF} = $time_diff;
$last_value{ $id }{PAYLOAD} = $payload;
}else{
$last_value{ $id }{TIME} = $now_milli;
$last_value{ $id }{DIFF} = "NA";
$last_value{ $id }{COUNT} = 1;
$last_value{ $id }{PAYLOAD} = $payload;
}
要获得当前时间(以毫秒为单位),您可以使用Time::HiRes qw/gettimeofday/
作为Perl核心的一部分:
use Time::HiRes qw/gettimeofday/;
my $now_milli = 1000 * gettimeofday();
最后,打印存储在%last_value
哈希中的信息:
foreach my $id (keys %last_value){
print "ID: ", $id, "\n";
print "Count: ", $last_value{$id}{COUNT}, "\n";
print "Time from last: ", $last_value{$id}{DIFF}, "\n";
print "Payload: ", $last_value{$id}{PAYLOAD}, "\n";
}