Perl分割字符串的一个精妙的写法

 1 #!/usr/bin/perl -w
 2 use strict;
 3 use warnings;
 4 
 5 #分割字符串的一个精妙的写法
 6 sub spliteName
 7 {
 8     my $fileName = shift ;
 9     my $arr_hash_ref = shift ;
10     open my $fd ,'<',$fileName or die "open file $fileName error!";
11     #文件格式如 :
12     #    girl: lily lucy may hallen # 关键字:名字(使用空格分开) 
13     while( <$fd> )
14     {
15         #这种方法先将属性项保存在$1中去掉,再将剩下的用splite分隔得到数组,非常精妙
16         next unless s/^(.+?):\s*// ;
17         $$arr_hash_ref{$1} = [ split ];
18     }
19 }
20 
21 sub main
22 {
23     my $fileName = "test.txt";
24     my %array_hash ;
25     spliteName($fileName,\%array_hash);
26     print_arr_hash(\%array_hash);
27 }
28 main();
29 
30 sub print_arr_hash
31 {
32     my $arr_hash_ref = shift ;
33     for my $key (keys %$arr_hash_ref)
34     {
35         #注意这里是打印整个数组, 所以记得加上 @ 
36         print "$key:@{$$arr_hash_ref{$key}} \n";
37     }
38 }
原文地址:https://www.cnblogs.com/trying/p/2876972.html