Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

perl - How to form hash from the contents of the following file?

I have not used hash before but I have a two files as shown below . How to put its contents into hash in such a way that PIO_M_U_PIO55_1 ,PIO_M_U_PIO55_2 etc becomes the keys and 896, 895 as its values so that its easy to access it in other files . Similarly for second file UART_10,UART_13 etc become the key and PIO_M_U_PIO55_1 etc as its value so that i can access 896 directly by UART_10. any other way is also welcomed...

 #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 ...
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There's two things you're trying to do. Parse a file, and insert into a hash. At a basic level, it goes like this:

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*defines+(w+)s+(w+)/  );
    $defines{$key} = $value;
}

print Dumper \%defines; 

That's all there is to it, really. A hash is an (unordered) set of key-value pairs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...