我之前没有使用哈希,但我有两个文件,如下所示。如何将其内容放入哈希,使PIO_M_U_PIO55_1 ,PIO_M_U_PIO55_2
等成为键,896, 895
作为其值,以便在其他文件中轻松访问它。同样,对于第二个文件UART_10,UART_13
等,将成为密钥,PIO_M_U_PIO55_1
等作为其值,以便我可以896
直接访问UART_10
。任何其他方式也欢迎...
#define PIO_M_U_PIO55_1 896
#define PIO_M_U_PIO55_2 895
#define PIO_M_U_PIO57_3 894
#define PIO_M_U_PIO55_4 893
and so on.....huge file
Similarly one more file
#define UART_10 PIO_M_U_PIO55_1
#define UART_13 PIO_M_U_PIO55_2
#define UART_11 PIO_M_U_PIO57_3
and so on ...
答案 0 :(得分:0)
你要做的事情有两件事。解析文件,并插入哈希。在基本层面上,它是这样的:
use strict;
use warnings;
use Data::Dumper;
my %defines;
open ( my $input_fh, "<", "input-file-name" ) or die $!;
while ( <$input_fh> ) {
my ( $key, $value ) = ( m/^\s*#\s*define\s+(\w+)\s+(\w+)/ );
$defines{$key} = $value;
}
print Dumper \%defines;
真的,这就是它的全部。散列是一组(无序)键值对。
答案 1 :(得分:0)
use strict;
use warnings;
my %hash;
while (<>) {
my ( $key, $value ) = /^\s*#\s*define\s+(\w+)\s+(\w+)/;
$hash{$key} = $value;
}
# substitute each value by other value if there is some present
# support transitivity
for my $value ( values %hash ) {
$value = $hash{$value} while exists $hash{$value};
}
# print out hash content as definitions with final values
print "#define $_ $hash{$_}\n" for sort keys %hash;
如果您怀疑可能有一个循环,您可以编写非常简单的循环检测;
for my $value ( values %hash ) {
my %seen; # cycle detection, stop when $value content is seen twice
$value = $hash{$value} while exists $hash{$value} and not $seen{$value}++;
}