- 论坛徽章:
- 0
|
原帖由 alen0826 于 2009-12-12 22:42 发表
请用电话上字母和数字的对应关系来来实现字母到数字的转换.
举个例子:
输入help,输出应为4357.
Sample code for learning Perl step by step:
- use strict;
- # create a hash for telefonkey's number and alphabet
- my %handykeys_num2chars = (
- 2 => 'abc',
- 3 => 'def',
- 4 => 'ghf',
- 5 => 'jkl',
- 6 => 'mno',
- 7 => 'qprs',
- 8 => 'tuv',
- 9 => 'wxyz',
- );
- my $word = 'ChinaUnix'; # i.e.: find related fon key's number from this word
- my $result_num = '';
- foreach my $char (split '', $word) // Split word in one char
- {
- # loop defined hash
- foreach my $key_num (sort keys %handykeys_num2chars) {
- # using regex to match the char and get related number
- if ($handykeys_num2chars{$key_num} =~ /$char/i) {
- $result_num .= $key_num; # put the found number together.
- }
- }
- }
- # print result
- print "$word => $result_num\n";
复制代码 |
|