How to put two array as key value pair in the hash using perl ?

Hello, I am having array @num which contains ASCII digit from 0 to 127 and the arrray @chars contains the associated ASCII character.
Now I want to put both array as a associative key => value pair in the hash %ascii. Could someone help me to do it please. Thanks!
perl -le '@num = ( 0..127 ); @chars = map (chr, @num); print "@chars"'

#now I want to do like this
perl -le 'print %ascii{97}'
#then it would print a

Open in new window

beer9Asked:
Who is Participating?
 
ozoCommented:
@num = ( 0..127 ); @chars = map (chr, @num); @ascii{@num}=@chars; print $ascii{97}

0
 
beer9Author Commented:
Just a clarification needed, why we are using @ascii{@num}=@chars
instead of
 %ascii{@num}=@chars

isn't it  %ascii would be hash and @ascii would be array.
Sorry if it is stupid question, but I just started learning perl. Thanks! :-)
0
 
ozoCommented:
 %ascii   is a hash, $ascii{97} is a scalar containing one value from the hash, @ascii{@num} is an array containing many values from the hash
see
perldoc  perldata
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
beer9Author Commented:
Thanks Ozo :-)

II got it and it's working fine for me, I am trying to get it in sorted by keys, but numbering order is quite different, it is not like below, any suggestion what I can do to get it :-)

0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
-
-
-
-
127
perl -le '@num = ( 0..127 ); @chars = map (chr, @num); @ascii{@num}=@chars; foreach $key ( sort (keys(%ascii)) ) { print $key, " => ", $ascii{$key} }'

Open in new window

0
 
ozoCommented:
since @num is sorted, you could use foreach $key ( @num )
but if that was not available you could use a numeric sort with <=> instead of cmp

foreach $key ( sort {$a <=> $b } keys %ascii )
0
 
beer9Author Commented:
Thanks for the awesome reply, I had just forgot @num.. but if @num is not sorted you mentioned
foreach $key ( sort {$a <=> $b } keys %ascii )
to use. Could you lease provide me some url link to understand what is $a and $b here. Thanks a lot!
0
 
ozoCommented:
since @num is sorted, you could use foreach $key ( @num )
but if that was not available you could use a numeric sort with <=> instead of cmp

foreach $key ( sort {$a <=> $b } keys %ascii )
0
 
ozoCommented:
perldoc -f sort
0
 
beer9Author Commented:
Thanks a lot Ozo! :-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.